gpt4 book ai didi

c++ - 派生类和基类之间指针到指针的转换?

转载 作者:可可西里 更新时间:2023-11-01 15:03:59 28 4
gpt4 key购买 nike

关于以下 C++ 程序:

class Base { };

class Child : public Base { };

int main()
{
// Normal: using child as base is allowed
Child *c = new Child();
Base *b = c;

// Double pointers: apparently can't use Child** as Base**
Child **cc = &c;
Base **bb = cc;

return 0;
}

GCC 在最后一个赋值语句中产生以下错误:

error: invalid conversion from ‘Child**’ to ‘Base**’

我的问题分为两部分:

  1. 为什么没有从 Child** 到 Base** 的隐式转换?
  2. 我可以使用 C 风格的转换或 reinterpret_cast 使这个示例工作。使用这些强制转换意味着放弃所有类型安全。有什么我可以添加到类定义中以使这些指针隐式转换,或者至少以允许我使用 static_cast 的方式来表达转换吗?

最佳答案

如果允许的话,你可以这样写:

*bb = new Base;

c 最终会指向 Base 的一个实例。不好。

关于c++ - 派生类和基类之间指针到指针的转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2532422/

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