c++智能指针多态
C++ smart pointers polymophism
我对智能指针很陌生,所以很抱歉,如果我的问题对你们中的一些人来说似乎很幼稚。下面是我想要做的一个例子:
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_ptr3
是shared_ptr
,因此.
操作符将访问shared_ptr
类的成员,而不是您的派生类。
还有,shared
是shared_ptr
吗?
相关文章:
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- Doees the 'this' 指针参与虚函数的多态行为
- 如何在基类指针向量的元素上应用重载的多态函数
- 具有智能指针的多态性
- 当目标指针不是基类的类型时,为什么允许dynamic_cast为多态类生成 null 指针?
- 如何模板化堆栈分配的多态指针数组到接口,包括派生类型的相应点?
- 如何使用静态多态性在 int 和指针类型之间进行转换?
- 无法初始化已知大小的矢量指针,该大小不会因多态性而更改
- 如何调用指针类型的方法(禁用多态性)?
- 当依赖关系和依赖关系都是多态时,在哪个继承级别存储依赖关系指针?
- 创建基类指针的向量并将派生类对象传递给它(多态性)
- 当我有多态指针时使用"rule of zero"
- 为什么我们使用多态指针
- 序列化多态指针的QVector
- 多态指针的类型id
- 指向成员函数的多态指针
- 使用多态指针调用函数
- 指向基类的基本多态指针
- 指向成员变量的多态指针
- 从多态指针检查类成员是否存在