我正在使用一个简单的逻辑模拟器程序中的数组,并希望转而使用向量进行学习,但我使用的参考书《C++面向对象编程》中关于向量和对象的内容不多,所以我有点迷茫。
以下是先前的代码:
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 ??
}
向量数组可以容纳不同类型的对象(AND门、OR门),但它们会继承向量数组的类型(门)吗?
<memory>
中获得一个shared_ptr
实现。针对你正在做的那种事情,你可能需要查看Boost指针容器。 - GManNickG