0

I am quite new to smart pointer so sorry if my question seems naive to some of you. Here is an example of what i want to do:

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();
}

Let say that i have extracted a shared pointer from myMap (lets call it myPointer), and that i want to use DerivedB specific (but not inherited virtual) functions. The compiled does not understand cause it thinks that myPointer (or object_ptr3 in the above example) is of Base type.

I tried casting it with static_pointer_cast and dynamic_pointer_cast (which in some cases does not work)... Any better id for handling these king of situations.

Thanks in advance

4

1 に答える 1

0

dynamic_pointer_castこの場合に機能する必要があります。キャスト中に何か間違ったことをしたのかもしれません。
次のようになります。

std::shared_ptr<Base> base(new Base);
std::shared_ptr<Derived> derived = std::dynamic_pointer_cast<Derived>(base);

コードをもう一度見てみると、問題は.object_ptr3.functionB();.代わりに->. object_ptr3は であるshared_ptrため、オペレーターは派生クラスではなくクラス.のメンバーにアクセスします。shared_ptr

また、sharedですかshared_ptr

于 2013-05-13T13:52:53.567 に答える