派生类和基类之间的指针到指针的转换? [英] Conversion of pointer-to-pointer between derived and base classes?
本文介绍了派生类和基类之间的指针到指针的转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
关于以下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**’
我的问题分为两部分:
- 为什么没有隐式转换Child ** to Base **?
- 我可以使用C风格的转换或
reinterpret_cast
使用这些铸件意味着丢弃所有类型的安全。有没有什么我可以添加到类定义,使这些指针隐式转换,或至少短语的转换,允许我使用static_cast
?
- Why is there no implicit conversion from Child** to Base**?
- I can make this example work with a C-style cast or a
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 usestatic_cast
instead?
推荐答案
如果允许,您可以这样写:
If this was allowed, you could write this:
*bb = new Base;
并且 c
Base
的实例。错误。
这篇关于派生类和基类之间的指针到指针的转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文