一、不加virtual的情况
include <iostream>
using namespace std;
class Shape
{
private:
public:
Shape();
~Shape();
double CalArea();
};
Shape::Shape()
{
cout << "Shape()" << endl;
}
Shape::~Shape()
{
cout << "~Shape()" << endl;
}
double Shape::CalArea()
{
cout << "Shape->CalArea()" << endl;
return 0;
}
//Circle类
class Circle : public Shape
{
private:
double mR; //直径
public:
Circle(double r);
~Circle();
double CalArea();
};
Circle::Circle(double r)
{
cout << "Circle()" << endl;
mR = r;
}
Circle::~Circle()
{
cout << "~Circle()" << endl;
}
double Circle::CalArea()
{
cout << "Circle->CalArea()" << endl;
return 3.14 * mR * mR;
}
//Rect类
class Rect : public Shape
{
private:
double mW;
double mH;
public:
Rect(double w, double h);
~Rect();
double CalArea();
};
Rect::Rect(double w, double h)
{
cout << "Rect()" << endl;
mW = w;
mH = h;
}
Rect::~Rect()
{
cout << "~Rect()" << endl;
}
double Rect::CalArea()
{
cout << "Rect->CalArea()" << endl;
return mW * mH;
}
int main()
{
Shape *s1 = new Rect(3, 6);
Shape *s2 = new Circle(5);
s1->CalArea();
s2->CalArea();
delete s1;
s1 = NULL;
delete s2;
s2 = NULL;
system("pause");
return 0;
}
运行效果:
Shape()
Rect()
Shape()
Circle()
Shape->CalArea()
Shape->CalArea()
~Shape()
~Shape()
请按任意键继续. . .
一、加上virtual关键字
class Shape
{
...
public:
virtual double CalArea(); //父类一定要加virtual
};
class Circle : public Shape
{
...
public:
...
virtual double CalArea(); //子类的virtual可以不加
};
class Rect : public Shape
{
...
public:
...
virtual double CalArea(); //子类的virtual可以不加
};
运行效果
Shape()
Rect()
Shape()
Circle()
Rect->CalArea()
Circle->CalArea()
~Shape()
~Shape()
请按任意键继续. . .