#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()
函数的实现,以满足基类中的虚函数要求。