C++ 多态实际应用代码
时间: 2023-11-14 14:17:14 浏览: 40
以下是一个简单的 C++ 多态实际应用代码示例:
```cpp
#include <iostream>
using namespace std;
class Shape {
protected:
int width, height;
public:
Shape( int a = 0, int b = 0) {
width = a;
height = b;
}
virtual int area() {
cout << "Parent class area :" <<endl;
return 0;
}
};
class Rectangle: public Shape {
public:
Rectangle( int a = 0, int b = 0):Shape(a, b) { }
int area () {
cout << "Rectangle class area :" <<endl;
return (width * height);
}
};
class Triangle: public Shape{
public:
Triangle( int a = 0, int b = 0):Shape(a, b) { }
int area () {
cout << "Triangle class area :" <<endl;
return (width * height / 2);
}
};
int main() {
Shape *shape;
Rectangle rec(10,7);
Triangle tri(10,5);
// 多态调用
shape = &rec;
shape->area();
shape = &tri;
shape->area();
return 0;
}
```
在上面的示例代码中,`Shape` 是一个基类,它有一个 `area()` 方法,这个方法被标记为 `virtual`,这意味着它可以被子类重写。
`Rectangle` 和 `Triangle` 是 `Shape` 的两个子类,它们都重写了 `area()` 方法。
在 `main()` 函数中,我们创建了一个指向 `Shape` 对象的指针 `shape`,然后我们将它分别指向 `Rectangle` 和 `Triangle` 对象,并调用它们的 `area()` 方法。由于 `area()` 方法被标记为 `virtual`,因此在运行时会根据实际对象的类型来确定要调用哪个版本的 `area()` 方法。这就是多态的应用。