我在一個簡單的邏輯模擬器程序中使用了一個數組,我想切換到使用一個向量來學習它,但是我使用的「Lafore的C++中的OOP」的引用沒有很多關於向量和對象,所以我我有點失落。不同類型的對象在同一個向量數組中?
這裏是以前的代碼:
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 ??
}
所以一個矢量數組保存不同類型的對象(ANDgate, - 門),但他們繼承矢量數組的類型(門)?
請不要這樣的手動內存管理。在*非常*最少獲得一個'shared_ptr'實現,無論是從Boost或TR1,還是C++ 0x的''。對於那種你正在做的事情,你可能想看看[Boost指針容器](http://www.boost.org/doc/libs/1_43_0/libs/ptr_container/doc/ptr_container.html)。 –
GManNickG
2010-08-13 08:15:03
我不知道什麼是shared_ptr :(我不明白其中的風險 – Ahmed 2010-08-13 08:26:02
shared_ptr不是風險,它們是風險緩解器,當編碼器忘記調用刪除它們的新分配時,它們負責刪除 – DumbCoder 2010-08-13 08:30:06