嗨,今天我问了一个关于How to insert different types of objects in the same vector array 的问题,我在这个问题中的代码是
gate* G[1000];
G[0] = new ANDgate() ;
G[1] = new ORgate;
//gate is a class inherited by ANDgate and ORgate classes
class gate
{
.....
......
virtual 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
}
我想使用向量,所以有人写道我应该这样做:
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 pointer containers
或shared_ptr
。在过去的3个小时里,我一直在阅读这个主题,但文档对我来说似乎相当高级。*谁能给我一个shared_ptr
用法的小代码示例,以及为什么他们建议使用shared_ptr
。还有其他类型,如ptr_vector
、ptr_list
和ptr_deque
*
Edit1:我也读过一个代码示例,其中包括:
typedef boost::shared_ptr<Foo> FooPtr;
.......
int main()
{
std::vector<FooPtr> foo_vector;
........
FooPtr foo_ptr( new Foo( 2 ) );
foo_vector.push_back( foo_ptr );
...........
}
而且我不懂语法!
https://stackoverflow.com/questions/3476938
复制相似问题