不同类型的对象在同一个向量数组? [英] different types of objects in the same vector array?
问题描述
我在一个简单的逻辑模拟器程序中使用数组,我想切换到使用向量来学习它,但我使用OOP在C ++中的Lafore的参考没有很多关于向量和对象
I am using an array in a simple logic simulator program and I want to switch to using a vector to learn it but the reference I am using "OOP in C++ by Lafore" doesn't have a lot about vectors and objects so I am kinda of lost .
这是以前的代码:
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 ??
}
因此矢量数组可以保存不同类型的对象它们继承了向量数组(门)的类型????
so can a vector array hold different types of objects(ANDgate , ORgate) but they inherit the type of the vector array (gate) ????
推荐答案
p>
You're half-way there:
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();
}
当然,这种方式你需要注意确保你的对象删除。我将使用智能指针类型的向量,例如 boost :: shared_ptr
来管理它。你可以只存储本地对象的地址(例如 G.push_back(& a)
),但是你需要确保指针在本地对象已被销毁。
Of course, this way you need to take care to ensure that your objects are deleted. I'd use a vector of a smart pointer type such as boost::shared_ptr
to manage that for you. You could just store the address of local objects (e.g. G.push_back(&a)
), but then you need to ensure that the pointers are not referenced after the local objects have been destroyed.
这篇关于不同类型的对象在同一个向量数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!