虚函数
虚函数很简单,就是在普通函数前面加个关键字virtual
#include <iostream>
#include <cmath>
using namespace std;
#define PI 3.14
//几何图形类
class Geometry{
public:
//获取面积
float getArea(){
return 0;
};
};
//矩形类
class Rectangle:public Geometry{//多态必须是共有继承
public:
Rectangle(float minX,float minY,float maxX,float maxY)
:minx(minX),miny(minY),maxx(maxX),maxy(maxY)
{
}
public:
float getArea(){
return fabs((minx-maxx)*(miny-maxy));
}
private:
float minx,miny,maxx,maxy;
};
//圆形类
class Circle:public Geometry{
public:
Circle(float R)
:r(R)
{
}
public:
float getArea(){
return PI*r*r; //常量M_PI就是这里的PI
}
private:
float r;
};
int main(int argc, const char * argv[]) {
Rectangle *re = new Rectangle(0,0,3,4);
cout<<re->getArea()<<endl;
delete re;//记得new关键字,需手动回收内存
Circle *c = new Circle(3);
cout<< c->getArea()<<endl;
delete c;
Geometry *ge = new Rectangle(0,0,3,4); //用父类的指针接收子类的对象
cout<<ge->getArea()<<endl;
delete ge;
return 0;
}
12
28.26
0
可以看到用父类的指针接收子类的对象,不能输出正常结果,怎么办呢?
#include <iostream>
#include <cmath>
using namespace std;
#define PI 3.14
//几何图形类
class Geometry{
public:
//获取面积
virtual float getArea(){
return 0;
};
};
//矩形类
class Rectangle:public Geometry{//多态必须是共有继承
public:
Rectangle(float minX,float minY,float maxX,float maxY)
:minx(minX),miny(minY),maxx(maxX),maxy(maxY)
{
}
public:
float getArea(){
return fabs((minx-maxx)*(miny-maxy));
}
private:
float minx,miny,maxx,maxy;
};
//圆形类
class Circle:public Geometry{
public:
Circle(float R)
:r(R)
{
}
public:
virtual float getArea(){ //这里不管写不写virtual,都是虚的
return PI*r*r; //常量M_PI就是这里的PI
}
private:
float r;
};
int main(int argc, const char * argv[]) {
Rectangle *re = new Rectangle(0,0,3,4);
cout<<re->getArea()<<endl;//12
delete re;//记得new关键字,需手动回收内存
Circle *c = new Circle(3);
cout<< c->getArea()<<endl;//28.26
delete c;
Geometry *ge = new Rectangle(0,0,3,4);
cout<<ge->getArea()<<endl;//12
delete ge;
//子类对象赋值给父类对象(不可以)
Circle circle(3);
Geometry g = circle;
cout<<g.getArea()<<endl; //0
//子类对象的地址赋值给父类对象的指针(可以)
Circle *c1 = new Circle(3);
Geometry *g1 = c1;
cout<< g1->getArea()<<endl;//28.26
delete c1;
//子类对象赋值给父类对象的引用(可以)
Circle c2(3);
Geometry& g2 = c2;
cout<< g2.getArea()<<endl;//28.26
return 0;
}
12
28.26
12
0
28.26
28.26
父类方法是虚的,不管子类写不写都是虚的。为了代码的可读性,建议子类写上virtual
关键字