#include<stdio.h>
class Shape{
public:
Shape(int width,int height):mWidth(width),mHeight(height){
printf("shape constructor\n");
}
long getArea(){
printf("shape getArea,width=%d,height=%d\n",mWidth,mHeight);
return 0;
}
int mWidth,mHeight;
};
class Rectangle:public Shape{
public:
Rectangle(int width,int height):Shape(width,height){
printf("rectangle constructor\n");
}
long getArea(){
printf("rectangle getArea,width=%d,height=%d\n",mWidth,mHeight);
return 0;
}
};
void function(Shape *shape){
shape->getArea();
}
int main(){
Shape shape(1,2);
Rectangle rectangle(3,4);
function(&shape);
function(&rectangle);
}
log打印:
shape constructor
shape constructor
rectangle constructor
shape getArea,width=1,height=2
shape getArea,width=3,height=4
virtual关键字作用于函数动态绑定,可以实现C++的运行时多态
#include<stdio.h>
class Shape{
public:
Shape(int width,int height):mWidth(width),mHeight(height){
printf("shape constructor\n");
}
virtual long getArea();
int mWidth,mHeight;
};
long Shape::getArea(){
printf("shape getArea,width=%d,height=%d\n",mWidth,mHeight);
return 0;
}
class Rectangle:public Shape{
public:
Rectangle(int width,int height,int count):Shape(width,height),mCount(count){
printf("rectangle constructor,mcount=%d\n",mCount);
}
virtual long getArea();
private:
int mCount;
};
long Rectangle::getArea(){
printf("rectangle getArea,width=%d,height=%d\n",mWidth,mHeight);
return 0;
}
void function(Shape *shape){
shape->getArea();
}
int main(){
Shape shape(1,2);
Rectangle rectangle(3,4,1);
function(&shape);
function(&rectangle);
}
gcc virtual_method.cpp -fno-rtti编译后运行log打印:
shape constructor
shape constructor
rectangle constructor,mcount=1
shape getArea,width=1,height=2
rectangle getArea,width=3,height=4
注意:
- 一般成员函数可以是虚函数
- 构造函数不能是虚函数
- 析构函数可以是虚函数(多态基类应该声明virtual析构函数,否则通过基类去析构派生类成员会导致析构不彻底,引起内存泄漏)