将指针从一种基类型转换为另一种基类型

时间:2012-07-16 16:30:20

标签: c++ pointers

- 编辑 -

感谢您的快速回复,我的代码遇到了非常奇怪的问题,我将我的演员阵容更改为dynamic_cast并且现在完全正常工作

-ORIGINAL POST -

将一个基类的指针强制转换为另一个基类是否安全?为了扩展这一点,我在下面的代码中标记的指针是否会导致任何未定义的行为?

class Base1
{
public:
   // Functions Here
};


class Base2
{
public:
   // Some other Functions here
};

class Derived: public Base1, public Base2
{
public:
  // Functions
};

int main()
{
  Base1* pointer1 = new Derived();
  Base2* pointer2 = (Base2*)pointer1; // Will using this pointer result in any undefined behavior?
  return 1;
}

2 个答案:

答案 0 :(得分:12)

  

使用此指针会导致任何未定义的行为吗?

是。 C风格的演员阵容只会尝试以下演员阵容:

  • const_cast
  • static_cast
  • static_cast,然后是const_cast
  • reinterpret_cast
  • reinterpret_cast,然后是const_cast

它将使用reinterpret_cast并做错了。

如果Base2具有多态性,即具有virtual个函数,则此处的正确转换为dynamic_cast

Base2* pointer2 = dynamic_cast<Base2*>(pointer1);

如果它没有虚函数,则不能直接执行此操作,需要先将其转换为Derived

Base2* pointer2 = static_cast<Derived*>(pointer1);

答案 1 :(得分:0)

您应该使用dynamic_cast运算符。如果类型不兼容,则此函数返回null。