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();使用 a.而不是 a调用->object_ptr3是 a shared_ptr,因此.运算符将访问shared_ptr该类的成员,而不是您的派生类。

另外,是shared一个shared_ptr

于 2013-05-13T13:52:53.567 回答