用vector<boost::any>,不熟
先创建一个基类,vector元素类型为基类:vector<father*>;
把不同类型都写成同一个基类的派生类,在各自的派生类里面添加自己的数据类型,然后实例化,在push_back()进去
需要使用的时候,再把vec中的元素转化成子类返回;
在需要删除容器里的数据时,需要手动将类delete,不然会内存泄漏。
class Father { public: std::string flag = "I am Father"; }; class ChildOne :public Father { public: std::string c1_flag = "I am ChildOne"; int c1_data = 999; }; class ChildTwo :public Father { public: std::string c2_flag = "I am ChildTwo"; std::string c2_data = "ChildTwo Data"; }; Father * father = new Father(); cout << "father:" << father->flag << endl; ChildOne *c1 = new ChildOne(); cout << "childone:" << c1->flag << endl; ChildTwo *c2 = new ChildTwo(); cout << "childtwo:" << c2->flag << endl; vector<Father*>*f_vec = new vector<Father*>; f_vec->push_back(c1); f_vec->push_back(c2); cout << "c1:" << static_cast<ChildOne*>(f_vec->at(0))->flag <<";"<< static_cast<ChildOne*>(f_vec->at(0))->c1_data << endl; cout << "c2:" << static_cast<ChildTwo*>(f_vec->at(1))->flag <<";"<< static_cast<ChildTwo*>(f_vec->at(1))->c2_data << endl;