在C++中,std::vector
是一个动态数组容器,它可以存储同一类型的对象。要实现多态性,可以将std::vector
声明为存储指向基类的指针或引用,然后将派生类对象的指针添加到该向量中。通过这种方式,您可以实现基于多态性的对象操作。
#include <iostream>
#include <vector>
using namespace std;
class Shape {
public:
virtual void draw() const {
cout << "Drawing a shape." << endl;
}
virtual ~Shape() {} // 基类的析构函数需要是虚函数,以便正确调用派生类的析构函数
};
class Circle : public Shape {
public:
void draw() const override {
cout << "Drawing a circle." << endl;
}
};
class Square : public Shape {
public:
void draw() const override {
cout << "Drawing a square." << endl;
}
};
int main() {
vector<Shape*> shapes;
shapes.push_back(new Circle());
shapes.push_back(new Square());
for (const auto& shape : shapes) {
shape->draw(); // 由于draw是虚函数,将根据实际对象类型调用正确的版本
}
// 清理堆上分配的内存
for (const auto& shape : shapes) {
delete shape;
}
return 0;
}
如果要在C++中实现多态性的类实例数组,您可以使用指向基类的指针数组,然后将派生类对象的指针存储在数组中。
#include <iostream>
using namespace std;
class Shape {
public:
virtual void draw() const {
cout << "Drawing a shape." << endl;
}
virtual ~Shape() {} // 基类的析构函数需要是虚函数,以便正确调用派生类的析构函数
};
class Circle : public Shape {
public:
void draw() const override {
cout << "Drawing a circle." << endl;
}
};
class Square : public Shape {
public:
void draw() const override {
cout << "Drawing a square." << endl;
}
};
int main() {
const int size = 2;
Shape* shapes[size];
shapes[0] = new Circle();
shapes[1] = new Square();
for (int i = 0; i < size; ++i) {
shapes[i]->draw(); // 由于draw是虚函数,将根据实际对象类型调用正确的版本
}
// 清理堆上分配的内存
for (int i = 0; i < size; ++i) {
delete shapes[i];
}
return 0;
}