使用C++定义一个基类Shape,在此基础上派生出Rectangle和Circle类,二者都有Getarea()计算对象面积。使用Rectangle类创建一个派生类Square
时间: 2024-05-10 13:18:42 浏览: 15
以下是C++代码实现:
```
#include <iostream>
using namespace std;
class Shape {
public:
virtual double GetArea() = 0; // 纯虚函数,需要在派生类中实现
};
class Rectangle : public Shape {
public:
Rectangle(double w, double h) : width(w), height(h) {}
double GetArea() override { return width * height; } // 实现基类中的纯虚函数
protected:
double width;
double height;
};
class Circle : public Shape {
public:
Circle(double r) : radius(r) {}
double GetArea() override { return 3.14159 * radius * radius; } // 实现基类中的纯虚函数
protected:
double radius;
};
class Square : public Rectangle {
public:
Square(double w) : Rectangle(w, w) {} // 正方形的长和宽相等
};
int main() {
Rectangle rect(3, 4);
Circle circle(5);
Square square(6);
cout << "Rectangle area: " << rect.GetArea() << endl;
cout << "Circle area: " << circle.GetArea() << endl;
cout << "Square area: " << square.GetArea() << endl;
return 0;
}
```
输出:
```
Rectangle area: 12
Circle area: 78.5398
Square area: 36
```