我對智能指針相當陌生,所以很抱歉,如果我的問題似乎對你們中的一些人天真。 這裏是我想要做的一個例子:C++智能指針多態主義
using namespace std;
class Base
{
protected:
int m_Property;
public:
virtual function() {...;}
}
class DerivedA : public Base
{
public:
virtual function() {second implementation...;}
virtual functionA() {...;}
}
class DerivedB : virtual public Base, public DerivedA
{
public:
virtual functionB() {...;}
}
void main()
{
map<int, shared_ptr<Base>> myMap;
shared_ptr<Base> object_ptr1 = shared_ptr<Base>(new Base());
shared_ptr<Base> object_ptr2 = shared_ptr<Base>(new DerivedA());
shared_ptr<Base> object_ptr3 = shared_ptr<Base>(new DerivedB());
myMap.insert(pair<int, shared_ptr<Base>>(1,object_ptr1));
myMap.insert(pair<int, shared_ptr<Base>>(2,object_ptr2));
myMap.insert(pair<int, shared_ptr<Base>>(3,object_ptr3));
// What i want to do (cause I know for sure that object_ptr3 points to a DerivedB object):
object_ptr3->functionB();
}
讓我們說,我已經解壓縮MYMAP共享光標(可以稱之爲myPointer),並且我想使用DerivedB具體的(但不是繼承虛) 功能。 編譯不明白的原因它認爲myPointer(或上面例子中的object_ptr3)是Base類型的。
我試着用static_pointer_cast和dynamic_pointer_cast(它在某些情況下不起作用)鑄造它... 任何更好的處理這些情況之王的id。
在此先感謝
'dynamic_pointer_cast'或'static_pointer_cast'應該按預期工作。你能告訴我們你是如何使用它們以及它失敗的嗎? – syam 2013-05-13 13:44:26
「共享」一個新模板還是一個錯字? – 2013-05-13 13:50:53
這是編譯器消息: 1> c:\ program files \ microsoft visual studio 11.0 \ vc \ include \ memory(369):error C2635:無法將'Base *'轉換爲'DerivedC *';隱含從虛擬基類轉換 問題是我有多重繼承:DerivedC繼承自Base和DerivedA。所以我用虛擬來避免「Base」類雙重繼承的問題 – Laurent 2013-05-13 13:58:01