题目
定义一个基类Shape,在此基础上派生出Rectangle和Circle,二者都有getArea()的成员函数计算对象的面积。使用Rectangle类创建一个派生类Square。
源代码
#include "stdafx.h"
#include<iostream>
using namespace std;
class shape {
public:
shape() {};
~shape() {};
virtual float getArea() {return 0;}
};
class circle :public shape {
public:
circle(float r) :R(r) {};
~circle() {};
float getArea() {return 3.14*R*R;}
private:
float R;
};
class rectangle :public shape {
public:
float len;
float width;
rectangle(float len, float width) : l(len), w(width) {};
~rectangle() {};
virtual float getArea() { return l*w; }
virtual float getLen() { return l; }
virtual float getWidth() { return w; }
private:
float l;
float w;
};
class square :public rectangle {
public:
square(float len);
~square() {};
};
square::square(float len) :rectangle(len, len){}
int _tmain(int argc, _TCHAR* argv[])
{
shape *p;
p = new circle(2);//设定测试值
cout << "Circle的面积是" << p->getArea() << endl;
delete p;
p = new rectangle(2, 3);//设定测试值
cout << "Rectangle的面积是" << p->getArea() << endl;
delete p;
p = new square(5);//设定测试值
cout << "Square的面积是" << p->getArea() << endl;
delete p;
return 0;
}
测试运行结果
解析
在这里shape类是几何图形的基类,在类中不包含有可以计算几何图形面积的函数,但是在派生类rectangle、circle和square中,各自包含有计算几何图形面积的功能,而在主函数中,定义一个基类的指针,然后通过指针指向各个派生类中成员函数,从而计算分别计算出几何图形面积。