如何将接口对象强制转换为特定的继承对象

1 c++ casting class type-conversion c++11

我有一个接口类:

Class IOperand
{
    virtual ~IOperand() {};

    virtual std::string  getType() const = 0;
}
Run Code Online (Sandbox Code Playgroud)

我有几个像这样继承的类:

class Int8: public IOperand
{
    public:
      Int8(int8_t _value = 0);
      virtual ~Int8() {};
      virtual std::string getType() const;

      int8__t  getValue() const;

    private:
      int8_t _value
}
Run Code Online (Sandbox Code Playgroud)

我在IOperand类型上使用指针,但我需要使用getValue()成员函数.如何在子类类型对象中转换IOperand类型对象,具体取决于getType()的返回值(返回一个包含目标子类名称的字符串.)?

Mic*_*yan 5

您要求将基类型转换为派生类型.通常这种铸造是设计不良的标志,因为 - 在大多数情况下 - 基础类型应该提供提供所需操作的虚拟方法.但是,在某些情况下,有必要投射到特定的类.有两种方法可以做到这一点.

未知的运行时类型
如果您不知道该类型是否为Int8,则需要进行多态下击.这是通过这样的特殊dynamic_cast机制完成的:

IOperand* operand = // ...
Int8* casted = dynamic_cast<Int8*>(operand);
if (casted == nullptr) {
   // runtime type was not an Int8
   return;
}
// operate on casted object...
Run Code Online (Sandbox Code Playgroud)

已知的运行时类型
如果您确定该类型是子类型,那么您可能希望使用a static_cast.但请注意,a static_cast不会进行检查dynamic_cast.但是,执行a会明显更快static_cast,因为它不需要任何反射或遍历继承树.