您的位置:首页 > 其它

用抽象类设计计算二维平面图形面积的程序

2013-11-16 18:26 1001 查看
在基类TDshape中设计纯虚函数area()和printName(),area()用于计算几何图形的面积,printName()用语打印输出几何图形的类名,如Triangle类的对象就打印输出“”Triangle“。每个具体形状的类则从抽象类TDshape派生,各自需要定义其独有的数据成员和成员函数,并且定义area()和printName()的具体实现代码。要求编写以TDshape为接口的函数,借以访问具体类如Triangle和Rectangle类的成员函数area(),printName()。

代码:

#include"iostream"
using namespace std;
class TDshape{
public:
virtual double area()=0;
virtual void printName()=0;
};

class Triangle:public TDshape{
private:
double width,height;
public:
double area(){
return (width*height/2);
}
void printName(){
cout << "Triangle" ;
}

void getwidth(double a=0){
width=a;
}
void getheight(double a=0){
height=a;
}
double setwidth(){
return width;
}
double setheight(){
return height;
}
};

class Rectangle:public TDshape{
private:
double width,height;
public:
double  area(){
return (width*height);
}
void printName(){
cout << "Rectangle" ;
}
void getwidth(double a=0){
width=a;
}
void getheight(double a=0){
height=a;
}
double setwidth(){
return width;
}
double setheight(){
return height;
}
};

void vpf(TDshape *p){
p->area();
p->printName();
cout << "Area =  " << p->area() << endl;
}

void main()
{
Triangle t;
t.getwidth(2);
t.getheight(2);
Rectangle r;
r.getwidth(2);
r.getheight(2);
TDshape *td[2];
td[0]=&t;
td[1]=&r;
for(int i=0;i<2;i++)
vpf(td[i]);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐