9

-编辑-

感谢您的快速响应,我的代码遇到了非常奇怪的问题,我将演员表更改为 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;
}
4

2 回答 2

13

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

是的。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);
于 2012-07-16T16:32:57.753 回答
1

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

于 2012-07-16T16:33:29.867 回答