我在一个简单的逻辑模拟器程序中使用数组,我想切换到使用 vector 来学习它,但是我使用的引用资料“Lafore 的 C++ 中的 OOP”没有太多关于 vector 和对象的内容,所以我有点迷路了。
这是之前的代码:
gate* G[1000];
G[0] = new ANDgate() ;
G[1] = new ORgate;
//gate is a class inherited by ANDgate and ORgate classes
class gate
{
.....
......
void Run()
{ //A virtual function
}
};
class ANDgate :public gate
{.....
.......
void Run()
{
//AND version of Run
}
};
class ORgate :public gate
{.....
.......
void Run()
{
//OR version of Run
}
};
//Running the simulator using overloading concept
for(...;...;..)
{
G[i]->Run() ; //will run perfectly the right Run for the right Gate type
}
现在我要做的是
vector(gate*) G;
ANDgate a
G.push_back(a); //Error
ORgate o
G.push_back(o); //Error
for(...;...;...)
{
G[i]->Run(); //Will this work if I corrected the error ??
}
vector 数组可以容纳不同类型的对象(AND 门、OR 门)但它们继承了 vector 数组(门)的类型吗????
最佳答案
你已经完成一半了:
std::vector<gate*> G;
G.push_back(new ANDgate);
G.push_back(new ORgate);
for(unsigned i=0;i<G.size();++i)
{
G[i]->Run();
}
当然,这种方式你需要注意确保你的对象被删除。我会使用智能指针类型的 vector ,例如 boost::shared_ptr
来为您管理它。您可以只存储本地对象的地址(例如 G.push_back(&a)
),但是您需要确保在销毁本地对象后不会引用指针。
关于c++ - 同一 vector 数组中的不同类型的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3475030/