c++智能指针多态

C++ smart pointers polymophism

本文关键字:多态 指针 智能 c++      更新时间:2023-10-16

我对智能指针很陌生,所以很抱歉,如果我的问题对你们中的一些人来说似乎很幼稚。下面是我想要做的一个例子:

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来铸造它(在某些情况下不起作用)…有没有更好的方法来处理这些情况呢?

Thanks in advance

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_ptr3shared_ptr,因此.操作符将访问shared_ptr类的成员,而不是您的派生类。

还有,sharedshared_ptr吗?