关于下面的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的方式表达转换?