矢量迭代铸造 [英] Vector Iterators Casting
本文介绍了矢量迭代铸造的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嘿,在C ++中,我有一个类型的向量:
Hey, In C++, I have a vector of type:
vector<BaseClass*> myVector;
其中,我插入(push_back)派生类的指针。
In which, I insert (push_back) pointers of derived classes into it.
现在,我想弹出它的元素,所以我这样做:
Now, I want to pop back its elements so I do this:
vector<ADlgcDev*>::iterator iter;
for (iter = myVector.rbegin(); iter != myVector.rend(); iter++)
{
// but before I pop it, I need to shutdown it down
// so I cast this
// but this way, I'm unable to call the function
(DerivedClass*(*iter))->Shutdown();
myVector.pop_back();
}
但是在我弹出之前的注释中,我需要调用它关闭()方法,投射也无法正常工作。任何决议?或者不可能?
but as mention in the comments before I pop it, I need to call its Shutdown() method and the cast is not working properly too. Any resolutions? or is impossible?
推荐答案
while (!myVector.empty())
{
((DerivedClass*)(myVector.back()))->Shutdown();
myVector.pop_back();
}
注意:
- 您应该使用
dynamic_cast
而不是强制转换。 (如果确定向量中只有DerivedClass
对象,为什么不是std :: vector< DerivedClass>
?) - 你可能不需要强制转换,因为
Shutdown()
应该在基类中声明。 - 您应该也可以删除对象,然后将其从向量中弹出。
- 你应该使用一个智能指针调用
Shutdown()
(和delete
,可能)。
- You should probably use
dynamic_cast
instead of the hard cast. (If it's sure that there are onlyDerivedClass
objects in the vector, why isn't itstd::vector<DerivedClass>
?) - You should probably not have to cast at all, since
Shutdown()
should be declared in the base class. - You should probably delete the objects, too, before you pop them off the vector. (But that might not be so.)
- You should probably use a smart pointer which calls
Shutdown()
(anddelete
, probably).
编辑:使用 std :: vector< T> :: clear )
,如markh44 所示可能比 pop_back()
。
Using std::vector<T>::clear()
, as shown by markh44 is probably better than the pop_back()
.
这篇关于矢量迭代铸造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文