关于以下 C++ 程序:
Regarding the following C++ program:
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 在最后的赋值语句上产生以下错误:
GCC produces the following error on the last assignment statement:
error: invalid conversion from ‘Child**’ to ‘Base**’
我的问题分为两部分:
reinterpret_cast
使这个示例工作.使用这些强制转换意味着抛弃所有类型安全.有什么我可以添加到类定义中以使这些指针隐式转换的,或者至少以一种允许我使用 static_cast
的方式来表达转换?reinterpret_cast
. Using these casts means throwing away all type safety. Is there anything I can add to the class definitions to make these pointers cast implicitly, or at least phrase the conversion in a way that allows me to use static_cast
instead? 如果允许,你可以这样写:
If this was allowed, you could write this:
*bb = new Base;
而且c
最终会指向Base
的一个实例.不好.
And c
would end up pointing to an instance of Base
. Bad.
这篇关于派生类和基类之间指针到指针的转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!