用面向对象的方法进行设计

本文介绍了一个使用C++实现的图形面积计算与展示的应用程序。该程序定义了抽象类Shape及其实现类Rectangle(矩形)、Circle(圆形)和Square(正方形),并演示了如何通过基类指针调用派生类的方法来计算和打印不同图形的面积。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

编写一个与图形相关的应用程序,需要处理大量图形(Shape)的信息。图形有矩形(Rectangle),圆形(Circle)和正方形(Square),应用需要计算这些图形的面积并且可能在设备上进行显示。




#include <map>
#include <queue>
#include <stack>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>


using namespace std ;


#define PI 3.14159


class Shape
{     //抽象类
public:
    Shape(){}
    ~Shape(){}
    virtual void Draw() = 0 ; //纯虚函数
    virtual double Area() = 0 ; //纯虚函数
} ;


//长方形类
class Rectangle : public Shape
{
private:
    int a;
    int b;
public:
    Rectangle():a(0),b(0){}
    Rectangle(int x,int y):a(x),b(y){}
    virtual void Draw()
    {
        cout<<"Retangle , Area = "<<Area()<<endl;
    }
    virtual double Area()
    {
        return a*b ;
    }
} ;


//圆形类
class Circle : public Shape
{
private:
    double r;
public:
    Circle(double x):r(x){}
    virtual void Draw()
    {
        cout<<"Circle , Area = "<<Area()<<endl;
    }
    virtual double Area()
    {
        return r*r*PI;
    }
} ;


//正方形类,继承Rectangle类
class Square : public Rectangle
{
private:
    int a ;
public:
    Square(int x):a(x){}
    virtual void Draw()
    {
        cout<<"Square , Area = "<<Area()<<endl;
    }
    virtual double Area()
    {
        return a*a;
    }
} ;


int main()
{
    Rectangle rect(10,20);
    Square square(10);
    Circle circle(8);


    Shape *p ;  //基类(抽象类)指针
    p = &rect ;
    cout<<p->Area()<<endl;
    p->Draw();


    p = &square ;
    cout<<p->Area()<<endl;
    p->Draw();


    p = &circle ;
    cout<<p->Area()<<endl;
    p->Draw();


    return 0 ;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值