版权声明:本文为博主原创文章,未经博主允许不得转载。如有问题,欢迎指正。 https://blog.csdn.net/zhouchangyu1221/article/details/89813219
// C++ 第五章:继承和虚函数(2)
// 2.虚函数的定义和使用
// 以纯虚函数为例
// 纯虚函数
// virtual 返回类型 函数名(参数表)=0;
#include<iostream>
using namespace std;
#define PI 3.1415
class Shape
{
public:
virtual float Area() = 0;
};
class Rect :public Shape
{
private:
float left;
float top;
float width;
float height;
public:
Rect()
{
left = 0;
top = 0;
width = 0;
height = 0;
}
Rect(float x, float y, float w, float h)
{
left = x;
top = y;
width = w;
height = h;
}
float Area()
{
return width*height;
}
};
class Circle :public Shape
{
float xCenter, yCenter, radius;
public:
Circle()
{
xCenter = 0;
yCenter = 0;
radius = 0;
}
Circle(float x, float y, float r)
{
xCenter = x;
yCenter = y;
radius = r;
}
float Area()
{
return PI*radius*radius;
}
};
int main(void)
{
Shape *p;
Rect R1(2, 1, 3.3, 2.0);
// 指向子类对象的指针
p = &R1;
cout << "矩形面积:" << p->Area() << endl;
// 指向子类对象的引用
Shape &r = R1;
cout << "矩形面积:" << r.Area() << endl;
// 指向子类对象的指针
p = new Circle(0, 0, 2.0);
cout << "圆形面积:" << p->Area() << endl;
return 0;
}