【发布时间】:2011-03-29 08:24:21
【问题描述】:
我在一个简单的逻辑模拟器程序中使用了一个数组,我想切换到使用向量来学习它,但是我使用的参考资料“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,ORgate),但它们继承了向量数组的类型(门)????
【问题讨论】:
-
请不要这样手动管理内存。至少非常从 Boost 或 TR1 或 C++0x 的
<memory>中获得shared_ptr实现。对于你正在做的那种事情,你可能想看看Boost pointer containers。 -
我不知道什么是 shared_ptr :( 而且我不明白这样做的风险。
-
shared_ptr 不是风险,它们是风险缓解剂。当编码人员忘记在他们的新分配上调用 delete 时,他们会负责删除
-
感谢 GMan 提供有用的链接