creating an array which can hold objects of different classes in C++

假如想象 提交于 2020-02-20 08:48:47

问题


How can I create an array which can hold objects of different classes in C++?


回答1:


If you want to create your own, wrap access to a pointer/array using templates and operator overloading. Below is a small example:

#include <iostream>

using namespace std;

template <class T>
class Array
{
private:
    T* things;

public:

    Array(T* a, int n) {
        things = new T[n];
        for (int i=0; i<n; i++) {
            things[i] = a[i];
        }
    }

    ~Array() {
        delete[] things;
    }

    T& operator [](const int idx) const {
        return things[idx];
    }
};

int main()
{    
    int a[] = {1,2,3};
    double b[] = {1.2, 3.5, 6.0};

    Array<int> intArray(a, 3);
    Array<double> doubleArray(b, 3);

    cout << "intArray[1]: " << intArray[1] << endl;
}



回答2:


You can use boost::any or boost::variant (comparing between the two: [1]).

Alternatively, if the "objects of different classes" have a common ancestor (say, Base), you could use a std::vector<Base*> (or std::vector<std::tr1::shared_ptr<Base> >), and cast the result to Derived* when you need it.




回答3:


define an base class and derive all your classes from this.

Then you could create a list of type(base*) and it could contain any object of Base type or derived type




回答4:


Have a look at boost::fusion which is an stl-replica, but with the ability to store different data types in containers



来源:https://stackoverflow.com/questions/2764671/creating-an-array-which-can-hold-objects-of-different-classes-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!