您的位置:首页 > 编程语言 > C语言/C++

c++容器存放不同结构的数据

2017-08-27 01:04 197 查看
本来想在c++容器里面存放不同的结构体,但是没有实现,最后通过子类父类的互相转换实现。

只要将建立一个基类的容器就可以直接push子类,这样就实现了一个可以用插入不同数据结构的容器。

1、将不同的结构体写成同一个基类派生的子类,在子类中添加自己希望的数据类型。

Test.h

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

2、将子类实例化并push到vector(其他容器也可以)

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);

3、在需要使用时,将vec中转换成基类的子类转回

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;
最后的结果:

c1:I am ChildOne;999
c2:I am ChildTwo;ChildTwo Data

4、注意事项

在需要删除容器里的数据时,需要手动将类delete,不然会内存泄漏。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ stl