这道C++编程题怎么做?如图所示,求大神解答~
1个回答
展开全部
示例代码:
#include<iostream>
#include<cmath>
using namespace std;
const double PI=3.14;
class Shape//抽象类
{
public:
virtual void Area()=0;//纯虚函数
};
class Rectangle:public Shape //继承方式必须为public
{
public:
Rectangle(int a1,int b1) {a=a1; b=b1;}
virtual void Area()
{
s=(a*b)/2.0;
cout<<"三角形面积为:"<<s<<endl;
}
private:
int a,b;
double s;
};
class Square:public Shape//矩形类
{
public:
Square(float a1, float b1) {a = a1, b = b1;}
virtual void Area()
{
s=a*b;
cout<<"矩形面积为:"<<s<<endl;
}
private:
float a, b;
double s;
};
class Circle:public Shape//圆类
{
public:
Circle(float myr) {r=myr;}
virtual void Area()
{
s=r*r*PI;
cout<<"圆的面积为:"<<s<<endl;
}
private:
float r;
double s;
};
void Show(Shape *p)//基类指针p
{
p->Area();
}
int main() {
double a, b;
cin>>a>>b;
Shape *p;//抽象类不能实例化但是可以定义指针或是引用
Rectangle Re(a, b);
p=ℜ//派生类对象地址赋给基类指针
Show(p);
Square Sq(a, b);
p=&Sq;
Show(p);
Circle C(a);
p=&C;
Show(p);
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询