c++ 定义一个抽象类CShape,包含纯虚函数 GetArea和纯虚函数SetData,然后派生出三角形CTriangle类、矩形

定义一个抽象类CShape,包含纯虚函数 GetArea(用来计算面积)和纯虚函数SetData(键盘输入数据),然后派生出三角形CTriangle类、矩形CRect类、圆CCircle类,要求:
1)分别求其面积,采用动态联编的方式输出面积信息;
2)重载>或<运算符,三类对象面积两两比较,求出面积最大者;
用c++编程

#include <iostream>
using namespace std;

class CShape{
public:
virtual double GetArea()const=0;
virtual void SetArea()=0;
};

class CTriangle:public CShape{
private:
double height;
double bottom;
public:
double GetArea()const{
return 0.5 * height * bottom;
}
void SetArea(){
cout<<"CTriangle.height:";cin>>this->height;
cout<<"CTriangle.bottom:";cin>>this->bottom;
}
bool operator>(const CShape& CBase){
//cout<<CBase.GetArea()<<endl;//
return this->GetArea() > CBase.GetArea();
}

};

class CRect:public CShape{
private:
double length;
double width;
public:
double GetArea()const{
return length * width;
}
void SetArea(){
cout<<"CRect.length:";cin>>this->length;
cout<<"CRect.width:";cin>>this->width;
}
bool operator>(const CShape& CBase){
//cout<<CBase.GetArea()<<endl;//
return this->GetArea() > CBase.GetArea();
}

};

class CCircle:public CShape{
private:
double radius;
public:
double GetArea()const{
return 3.141592654 * radius * radius;
}
void SetArea(){
cout<<"CCircle.radius:";cin>>this->radius;
}
bool operator>(const CShape& CBase){
//cout<<CBase.GetArea()<<endl;//
return this->GetArea() > CBase.GetArea();
}


};

int main(){
CTriangle ct;
ct.SetArea();
cout<<"CTriangle面积:"<<ct.GetArea()<<endl<<endl;

CRect cr;
cr.SetArea();
cout<<"CRect面积:"<<cr.GetArea()<<endl<<endl;

CCircle cc;
cc.SetArea();
cout<<"CCircle面积:"<<cc.GetArea()<<endl<<endl;

if(ct > cr && ct > cc)
cout<<"CTriangle面积最大!"<<endl;
else if(cr > ct && cr > cc)
cout<<"CRect面积最大!"<<endl;
else if(cc > ct && cc > cr)
cout<<"CCircle面积最大!"<<endl;
else
cout<<"最大值不唯一!"<<endl;

return 0;
}

 执行结果:

温馨提示:答案为网友推荐,仅供参考
相似回答