声明一个基类Shape,再派生出Rectangle类和Circle类

编写程序,声明一个基类Shape,再派生出Rectangle类和Circle类,二者都有GetArea()函数;计算对象的面积。使用程序Rectangle类创建一个派生类Square。

#include <iostream>
using namespace std;
class Shape//基类
{
    private:
        double R;
        double l;
        double w;
        double s;//私有数据,分别为半径,长宽,面积
    
    public:
    
        Shape(double a,double b,double c,double d)
        {
            R=a;
            l=b;
            w=c;
            s=d;
        }//构造函数初始化
        Shape(){
        };//构造函数
};

class Rectangle:public Shape//长方形类
{

    public:
        Rectangle() {
        };//构造函数
void getArea(double a,double b)//外部传入数据?
        {
    
            cout<<"面积"<<a*b<<endl;
            
        }//面积计算
    
};
class Circle:public Shape
{
    
    public:
        Circle(){
        };
    
void  getArea(double c)
        {
            
            cout<<"面积为"<<3.14*c*c<<endl;
        
        }
    
};
class Square:public Rectangle
{
    public :
        Square(){
        };
    void getArea(double d){
        cout<<"square"<<d*d<<endl;
    }
};
int main()
{
    double q,w,e,r;
    Shape shape(q,w,e,r);
    Rectangle rectangle;
    Circle circle;
    Square square;//建立相应对象
    Rectangle*p1;
    Circle*p2;
    Square*p3;
    p1=&rectangle;
    p2=&circle;
    p3=&square;//赋值操作
    cout<<"请输入圆的半径"<<endl;
    cin>>q;
    p2->getArea(q);
    cout<<endl;
    cout<<"请输入长方形的长和宽"<<endl;
    cin>>w>>e;
    p1->getArea(w,e);
    cout<<endl;
    cout<<"请输入正方形的边长"<<endl;
    cin>>r;
    p3->getArea(r);
    cout<<endl;
    
    
    
    return 0;
}

  • 5
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值