定义一个基类Shape,在此基础上派生出Rectangle和Circle,二者都有getArea()函数计算对象面积。使用Rectangle类创建一个派生类Square。

#include <iostream>
using namespace std;

const float pi = 3.14;

// 基类 Shape
class Shape {
public:
    virtual float getArea() const = 0; // 纯虚函数,需要子类实现
};

// 派生类 Rectangle
class Rectangle : public Shape {
private:
    float width;
    float height;
public:
    Rectangle(float w, float h) : width(w), height(h) {}

    float getArea() const override {
        return width * height;
    }
};

// 派生类 Circle
class Circle : public Shape {
private:
    float radius;
public:
    Circle(float r) : radius(r) {}

    float getArea() const override {
        return pi * radius * radius;
    }
};

// 派生类 Square
class Square : public Rectangle {
public:
    Square(float side) : Rectangle(side, side) {}
};

int main() {
    float a, b, r;
    cout << "Input a,b:";
    cin >> a >> b;
    cout << "Input r:";
    cin >> r;

    Rectangle rect(a, b);
    Circle circle(r);
    Square square(a); // 使用 Rectangle 类创建 Square 类

    cout << "Rectangle Area:" << rect.getArea() << ",Circle Area:" << circle.getArea() << endl;

    return 0;
}

【问题描述】

定义一个基类Shape,在此基础上派生出Rectangle和Circle,二者都有getArea()函数计算对象面积。使用Rectangle类创建一个派生类Square。

注:圆周率取3.14

【输入形式】

参考的输入(数字前面的文字为提示):

Input a,b:5 10

Input r:10

【输出形式】

参考的输出:

Rectangle Area:50,Circle Area:314

virtual float getArea() const = 0;

       这是一个纯虚函数声明。在 C++ 中,虚函数是通过在基类中声明并在派生类中重新定义来实现多态性的机制。将函数声明为纯虚函数意味着在基类中没有提供函数的实现,而是要求任何派生类都必须提供自己的实现。在这里,getArea() 函数是一个纯虚函数,因为它在基类中没有提供具体的实现(使用 = 0 表示),而是要求任何继承自 Shape 的子类都必须提供自己的 getArea() 函数实现。

float getArea() const override {
        return width * height;}

   getArea() 函数被标记为 override表明它是对基类 Shape 中的 getArea() 纯虚函数的重写。这有助于确保在 Rectangle 类中正确地提供了 getArea() 函数的实现,以满足基类中的虚函数要求。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值