[英]std::bad_cast from parent to child?
為簡單起見,
class Parent {}
class Child1 : Parent {}
class Child2 : Parent {}
在其他地方,我創建了Child1和Child2的實例,並將其存儲在Parent下的相同向量中:
// . . . in .h file, for example
vector<Parent> vector_of_parent;
// . . . in one particular method
Child1 c1;
Child2 c2;
vector_of_parent.push_back(c1);
vector_of_parent.push_back(c2);
// . . .
然后在另一個可以訪問vector_of_parent
方法中,我嘗試了
void doSomething(Parent& some_child) {
// wrapped in a try block somehow...
Child1& c = dynamic_cast<Child1&> some_child;
// do something if the cast is successful
}
void otherMethod() {
doSomething(vector_of_parent.at(0)); // vector_of_parent.at(0) is a Child1
}
為什么在我調用otherMethod()時出現std:bad_cast?
您的std::vector
聲明為std::vector<Parent>
。 它擁有的唯一實例Parent
-當您插入Child1
和Child2
情況下,他們得到切片 。
如果要使用具有Common Parent
基類的多態對象向量,則需要使用指針容器(或者,為了簡化生命周期和內存管理,使用智能指針)。
要考慮的適當容器類型包括std::vector<Parent*>
, std::vector<std::tr1::shared_ptr<Parent> >
和boost::ptr_vector<Parent>
。
我建議不要使用std::vector<Parent*>
除非您對手動內存管理非常滿意。
另外,您需要使用公共繼承而不是私有繼承,並且基類必須具有虛擬析構函數。 我認為您為簡潔起見就將其省略。
當你說:
vector<Parent> vector_of_parent;
您創建了父級向量-它可能不能包含子級對象。 如果要使用多態C ++容器,則該容器必須包含基類指針。 您的動態類型轉換失敗,因為您對其應用的對象始終是父對象,而不是子對象。
另外,從代碼中還不清楚,但是為了使用dynamic_cast,您的基類必須至少包含一個虛函數。
vector<Parent> vector_of_parent;
您正在創建Parent
對象的向量。 請注意,矢量將始終創建所傳遞對象的副本 。 所以當你做vector_of_parent.push_back(c1);
使用以下代碼創建c1的副本(為簡化起見,我忽略了分配器): T* pObj = new T(c1);
。 由於此處T的類型為Parent
,因此創建的副本的類型為Parent
。 因此,基本上發生了將子對象切成切片以從中創建父對象的情況。 現在,如果您嘗試將此Parent
對象動態_廣播為Child
類型,它將引發異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.