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

在基类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]);
}


  • 7
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值