c++ 计算几何图形面积(抽象类、虚函数的使用)

将一些类所具有的公共属性和方法放到基类中,避免重复定义。
定义基类Shape,在类中定义两个函数getName()、getArea()。分别用来获得类名称和面积。将getArea()定义为一个纯虚函数。

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

const double PI = 3.1415926;

class Shape
{
protected:
    char name[30];
public:
    Shape()
    {
        strcpy_s(name, "Shape");
    }
    char* getName()
    {
        return name;
    }

public:
    virtual double getArea() = 0;  //虚函数声明
};

class Circle: public Shape
{
private:
    double m_radius;
public:
    Circle(double radius)
    {
        strcpy_s(name, "Circle");
        m_radius = radius;
    }
    double getArea()
    {
        return PI * pow(m_radius, 2);
    }
};

class Rectangle: public Shape
{
private:
    double m_length;
    double m_width;
public:
    Rectangle(double length, double width)
    {
        m_length = length;
        m_width = width;
        strcpy_s(name, "Rectangle");
    }
    double getArea()
    {
        return m_length * m_width;
    }
};


void main(int argc, char* argv[])
{
    Circle circle(2);
    cout<<"shape name:"<<circle.getName()<<endl;
    cout<<"shape area:"<<circle.getArea()<<endl;
    Rectangle rectangle(3,2);
    cout<<"shape name:"<<rectangle.getName()<<endl;
    cout<<"shape area:"<<rectangle.getArea()<<endl;

    system("pause");
}

输出:
这里写图片描述

  • 5
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是用 C++ 设计一个抽象类计算面积的示例代码: ```c++ #include <iostream> using namespace std; // 抽象类 Shape class Shape { public: // 纯虚函数,计算面积 virtual float calcArea() = 0; }; // 派生类 Rectangle class Rectangle: public Shape { private: float width; float height; public: Rectangle(float w, float h) { width = w; height = h; } // 实现 Shape 中的纯虚函数 float calcArea() { return width * height; } }; // 派生类 Circle class Circle: public Shape { private: float radius; public: Circle(float r) { radius = r; } // 实现 Shape 中的纯虚函数 float calcArea() { return 3.14 * radius * radius; } }; int main() { // 创建对象 Shape *shape; Rectangle rec(3, 4); Circle cir(5); // 调用函数 shape = &rec; cout << "矩形的面积:" << shape->calcArea() << endl; shape = &cir; cout << "圆形的面积:" << shape->calcArea() << endl; return 0; } ``` 在这个示例代码中,我们首先定义了一个抽象类 Shape,其中有一个纯虚函数 calcArea(),这个函数用于计算图形面积。然后我们定义了两个派生类 Rectangle 和 Circle,它们分别实现了 calcArea() 函数。最后在 main() 函数中,我们创建了 Shape 类型的指针 shape,分别指向 Rectangle 和 Circle 对象,并调用 calcArea() 函数计算面积。 需要注意的是,抽象类是不能被实例化的,只有通过派生类来实现它的纯虚函数才能被实例化。同时,派生类在实现纯虚函数时,必须使用 virtual 关键字来声明。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值