关于以下 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**’
我的问题分为两部分:
- 为什么没有从 Child** 到 Base** 的隐式转换?
- 我可以让这个示例使用 C 风格的演员表或
reinterpret_cast
. 使用这些类型转换意味着抛弃所有类型安全。有什么我可以添加到类定义中以使这些指针隐式转换,或者至少以允许我使用的方式来表达转换static_cast
?