动态广播的操作数不是向下转换时的指针类型

问题描述 投票:0回答:2

我有一个基类:

class Base{
   public:
      Base();
      virtual ~Base();
      virtual void print(std::ostream& os) const = 0;
      .....
}

和两个派生类,Derived1从Base派生,Derived2从Derived1派生

class Derived1: public Base{
    protected:
       Derived1();
    public:
       virtual void print(std::ostream& os) const;
       .....
}


class Derived2: public Derived1{
    public:
       Derived2();
       virtual void print(std::ostream& os) const;
       ...
}

并且在我的主要语言中,我尝试将boost :: shared_ptr从基础动态转换为派生2:

  testFunction(boost:shared_ptr<Base> base){
     const Derived2*  derived2 = dynamic_cast<const Derived2*>(base);
}

错误是:

The operand of a dynamic_cast is not a pointer type

我该如何解决?谢谢!

c++ pointers dynamic-cast
2个回答
0
投票

提升为dynamic_pointer_cast

boost::shared_ptr<Derived2> derived2 = boost::dynamic_pointer_cast<Derived2>(base);

0
投票

dynamic_cast的操作数不是指针类型

我该如何解决?

通过不使用非指针类型作为dynamic_cast的操作数。换句话说,通过使用指针类型作为操作数。

您可以使用get成员函数从共享指针中获取指针。

请注意不要让这个裸露的指针泄漏到函数范围之外。仅当参数base指向对象时,您才能相信其有效性。


P.S。 std::shared_ptr自C ++ 11起就已存在于标准库中。

P.P.S。 dynamic_cast是一种代码气味。

© www.soinside.com 2019 - 2024. All rights reserved.