C++中如何实现多态?
时间: 2024-06-09 19:11:01 浏览: 16
在C语言中,可以通过使用抽象类和虚函数来实现多态。首先,需要定义一个抽象类,该抽象类包含至少一个纯虚函数。纯虚函数是通过在声明中使用"= 0"来指定的。抽象类是不允许被实例化的。然后,可以创建一个子类继承该抽象类,并且实现抽象类中的纯虚函数,这样就可以实现多态性。
以下是一个示例代码:
```
#include <iostream>
using namespace std;
class Shape {
public:
virtual void draw() = 0;
};
class Circle : public Shape {
public:
void draw() {
cout << "Drawing a circle" << endl;
}
};
class Rectangle : public Shape {
public:
void draw() {
cout << "Drawing a rectangle" << endl;
}
};
int main() {
Shape* shape;
Circle circle;
Rectangle rectangle;
shape = &circle;
shape->draw();
shape = &rectangle;
shape->draw();
return 0;
}
```
在上面的示例中,定义了一个抽象类Shape,其中包含一个纯虚函数draw()。然后创建了两个子类Circle和Rectangle,并分别实现了draw()函数。在main函数中,通过指针shape来指向不同的子类对象,然后调用draw()函数实现多态性。