今天碰到三个问题,现在来浅显地解答一下,算是回顾一下c++。
问题1.什么是虚函数(virtual function)。
问题2.虚函数怎么实现。
问题3.使用虚函数有什么代价
=================================================================================
问题1.
虚函数是指在继承类中可以被重新定义的成员函数,并且保留被调用的属性(纯虚函数不可以调用)。声明虚函数只要在一般的函数前面加上关键字 virtual。
问题2.
这个问题回答起来有些复杂。
首先,实现一个简单的虚函数。
#include <iostream>
using namespace std;
class Polygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b; }
virtual int area ()
{ return 0; }
};
class Rectangle: public Polygon {
public:
int area ()
{ return width * height; }
};
class Triangle: public Polygon {
public:
int area ()
{ return (width * height / 2); }
};
int main () {
Rectangle rect;
Triangle trgl;
Polygon poly;
Polygon * ppoly1 = ▭
Polygon * ppoly2 = &trgl;
Polygon * ppoly3 = &poly;
ppoly1->set_values (4,5);
ppoly2->set_values (4,5);
ppoly3->set_values (4,5);
cout << ppoly1->area() << '\n';
cout << ppoly2->area() << '\n';
cout << ppoly3->area() << '\n';
return 0;
}
20;
10;
0;下面,实现一个纯虚函数。包含纯虚函数的类属于抽象类。
#include <iostream>
using namespace std;
class Polygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b; }
virtual int area (void) =0;
};
class Rectangle: public Polygon {
public:
int area (void)
{ return (width * height); }
};
class Triangle: public Polygon {
public:
int area (void)
{ return (width * height / 2); }
};
int main () {
Rectangle rect;
Triangle trgl;
Polygon * ppoly1 = ▭
Polygon * ppoly2 = &trgl;
ppoly1->set_values (4,5);
ppoly2->set_values (4,5);
cout << ppoly1->area() << '\n';
cout << ppoly2->area() << '\n';
return 0;
}
10;
20;
说明:在基类class Polygon中,定义了纯虚函数 virtual int area()=0。
此时 class Ploygon 不能定义定义对象(抽象类不能定义对象)。
Polygon myPolygon; // 定义非法不过可以这样定义(定义指针)。Ploygon *ploygon1;
Ploygon *ploygon2;这时便可以实现c++中的多态了:将基类(Polygon)指针赋予不同继承类的对象的地址。
Rectangle rect;
Triangle trgl;
polygon1 = ▭
polygon2 = &trgl;虚函数area()会根据调用者的不同实现不同的功能。
polygon1->area(); // rectangular 类中的area() 起作用
polygon2->area(); // triangle 类中的area() 起作用
|
问题3.
这个问题比较高深,可以参考 |
http://www.cppblog.com/woaidongmao/archive/2008/05/22/50806.html
感谢这位作者的辛苦工作!
14万+

被折叠的 条评论
为什么被折叠?



