计算几何图形的面积
shape类表示几何图形,声明纯虚函数double area ().
triangle类表示三角形,包含属性double base (底),double hight (高),double area() (计算三角形面积)。
rectangle类表示矩形,包含属性double hight (高),double width (宽),double area (计算矩形面积)。
circle类表示圆形,包含属性double radius(半 径),double area() (计算圆形面积)。
在主函数中定义shape类指针,分别指向三个类的对象,并调用area()函数。
纯虚函数和抽象类。
纯虚函数重写接口;this指针指向内部参数。本次只写了矩形接口的虚函数。
#include <iostream>
using namespace std;
class shape{
public:
virtual double area()=0;
};
double shape::area(){
return 0;
}
class rectangle:public shape
{
public:
rectangle(double w,double h);
virtual double area();
private:
double width;
double hight;
};
rectangle::rectangle(double w,double h){
this->width=w;
this->hight=h;
}
double rectangle::area()
{
return this->witdh*this->hight;
}
int main()
{
shape* p=new rectangle(2,3);
cout<< p->area();
// return 0;
}