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

Rap*_*ael 8 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;
}
Run Code Online (Sandbox Code Playgroud)

R. *_*des 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);
Run Code Online (Sandbox Code Playgroud)

如果它没有虚函数,则不能直接执行此转换,需要先转换为Derived第一个.

Base2* pointer2 = static_cast<Derived*>(pointer1);
Run Code Online (Sandbox Code Playgroud)