gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 17:37:14 26 4
gpt4 key购买 nike

-编辑-

感谢您的快速响应,我的代码一直存在非常奇怪的问题,我将我的转换更改为 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;
}

最佳答案

Will using this pointer result in any undefined behavior?

是的。 C 风格的转换只会尝试以下转换:

  • const_cast
  • static_cast
  • static_cast,然后是 const_cast
  • 重新解释_cast
  • reinterpret_cast,然后是const_cast

它将使用 reinterpret_cast 并做错事。

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

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

如果没有虚函数,则不能直接进行这种类型转换,需要先转换为Derived

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

关于c++ - 将指针从一种基类型转换为另一种,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11508558/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com