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** 到 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_castinstead?
推荐答案
如果允许,你可以这样写:
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.
这篇关于派生类和基类之间指针到指针的转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
编程基础网
本文标题为:派生类和基类之间指针到指针的转换?
基础教程推荐
猜你喜欢
- c++ STL设置差异 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
