图形类的虚函数简单使用

代码 :

#include <iostream>
#include <iomanip>
#include <cmath>

#define PI acos(-1)

using namespace std;

//图形类
class Shape
{
protected:
    //周长和面积
    double perimeter;
    double aera;
public:
    //虚函数
    virtual void getPerimeter(){}
    virtual void getAera(){}
    virtual void show(){}
};

//圆类
class Circle: public Shape
{
private:
    int radius;  //半径
public:
    Circle() {cout<<"无参构造"<<endl;}
    Circle(int r):radius(r) {cout<<"构造一个圆形"<<"  半径为"<<radius<<endl;}
    void getPerimeter();  //重新构造周长
    void getAera();  //重新构造面积
    void show(){ cout<<"圆周长为"<<perimeter<<endl<<"圆面积为"<<aera<<endl; }
};

//矩形类
class Rect: public Shape
{
private:
    int length;  //长度
    int breadth;  //宽度
public:
    Rect() {cout<<"无参构造"<<endl;}
    Rect(int l, int b):length(l),breadth(b){cout<<"构造一个矩形"<<"  长度为"<<length<<"  宽度为"<<breadth<<endl;}
    void getPerimeter();  //重新构造周长
    void getAera();  //重新构造面积
    void show(){ cout<<"矩形周长为"<<setprecision(4)<<perimeter<<endl<<"矩形面积为"<<aera<<endl; }
};

void show(Shape* s)
{
    s->getAera();
    s->getPerimeter();
    s->show();
}

int main()
{
    Rect rect(5, 3);  //构造矩形类对象
    Circle circle(3);  //构造圆形类对象
    show(&rect);
    show(&circle);
    
    return 0;
}

void Circle::getPerimeter()
{
    perimeter = 2*PI*radius;
}

void Circle::getAera()
{
    aera = PI*radius*radius;
}

void Rect::getPerimeter()
{
    perimeter = 2 * (length + breadth);
}

void Rect::getAera()
{
    aera = length * breadth;
}

效果图:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值