C++类实例容器实现多态性

 在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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值