c++定义一个基类Shape,在此基础上派生出Rectangle和Circle,二者都有一个GetArea()函数计算对象面积。使用Rectangle类创建一个派生类Square。
时间: 2024-05-01 20:17:47 浏览: 180
Rectangle 矩形求面积 c++
好的,针对您的问题,以下是所需的代码实现:
```
class Shape {
public:
virtual double GetArea() = 0;
};
class Rectangle : public Shape {
private:
double width, height;
public:
Rectangle(double w, double h) {
width = w;
height = h;
}
double GetArea() {
return width * height;
}
};
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) {
radius = r;
}
double GetArea() {
return 3.14159 * radius * radius;
}
};
class Square : public Rectangle {
public:
Square(double s) : Rectangle(s, s) {}
};
int main() {
Shape* shape1 = new Rectangle(5, 10);
Shape* shape2 = new Circle(5);
Shape* shape3 = new Square(5);
cout << "Rectangle area: " << shape1->GetArea() << endl;
cout << "Circle area: " << shape2->GetArea() << endl;
cout << "Square area: " << shape3->GetArea() << endl;
delete shape1;
delete shape2;
delete shape3;
return 0;
}
```
上述代码中,Shape是基类,Rectangle和Circle是Shape的派生类。Square则是以Rectangle为基类的派生类。每个类都有一个GetArea()函数,用于计算图形的面积。在主函数中,我们创建了一个Rectangle对象、一个Circle对象和一个Square对象,并输出它们的面积。最后,记得释放已分配的内存。
阅读全文