定义一个Shape基类,其中包含纯虚函数GetArea(),在此基础上派生出Retangle和Circle类,二者都实现虚函数GetArea()的实现(计算对象面积)。在main函数中,使用Retangle和Circle类创建对象r和c,定义父类指针变量指向子类对象,调用GetArea()函数实现多态。(p=3.14)
时间: 2024-03-20 18:43:06 浏览: 37
下面是实现上述功能的示例代码:
```c++
#include <iostream>
using namespace std;
const double p = 3.14; // 定义常量p
class Shape {
public:
virtual double GetArea() = 0; // 声明纯虚函数GetArea()
};
class Rectangle : public Shape {
public:
Rectangle(double w, double h) : width(w), height(h) {}
double GetArea() override { // 实现GetArea()函数
return width * height;
}
private:
double width;
double height;
};
class Circle : public Shape {
public:
Circle(double r) : radius(r) {}
double GetArea() override { // 实现GetArea()函数
return p * radius * radius;
}
private:
double radius;
};
int main() {
Shape* pShape = nullptr;
Rectangle r(3, 4);
Circle c(2);
pShape = &r;
cout << "Rectangle area: " << pShape->GetArea() << endl;
pShape = &c;
cout << "Circle area: " << pShape->GetArea() << endl;
return 0;
}
```
输出结果为:
```
Rectangle area: 12
Circle area: 12.56
```
可以看到,通过多态性,父类指针变量pShape指向子类对象r和c,并调用了它们各自的GetArea()函数,输出了对应的面积值。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)