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



-EDIT-

感谢您的快速响应,我的代码出现了非常奇怪的问题,我将类型转换为dynamic_cast,现在它工作得很好

-原始后

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

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;
}

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

是的。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);

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

最新更新