【问题标题】:Casting pointer from one base type to another将指针从一种基本类型转换为另一种
【发布时间】:2012-07-16 16:30:20
【问题描述】:

-编辑-

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

【问题讨论】:

  • 你应该使用dynamic_cast,而不是C风格的演员。
  • 哦,Base2 是继承私有的,还是转录事故?如果是私人的,我的回答是不正确的!
  • 应该是public继承的,我打错了

标签: c++ pointers


【解决方案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);

【讨论】:

  • Base1 是多态的吗?可以改成Base2吗?
  • +1 但仍然试图弄清楚在这种情况下 static_cast 与 dynamic_cast 有什么不同,即使存在虚函数。
  • @Mahesh dynamic_cast 要求类是多态的(换句话说,有一个虚方法)。
  • @Mahesh 考虑另一种类型struct Derived2 : Base2, Base1 {};。在这种类型的对象上,从Base1Base2 的转换与问题上的类型不同:所需的指针调整不同。给定Base1*,编译器没有任何信息来决定哪些调整是正确的。所以,它需要:RTTI,这是dynamic_cast 使用的(基本上是一个 vptr),或者你明确地告诉它它正在处理什么类型。
  • @R.MartinhoFernandes 假设 Base1Base2 都是多态的,但仍然强制转换 Base2* pointer2 = dynamic_cast&lt;Base2*&gt;(pointer1); 不应该工作,不是吗?因为在这种情况下,Base1Base2 都没有直接关系
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2020-12-14
    • 2010-10-08
    • 1970-01-01
    • 2016-10-08
    • 2011-09-24
    • 1970-01-01
    相关资源
    最近更新 更多