C++ forbidden pointer to pointer conversion(C++禁止指针到指针转换)
问题描述
在 C++ 中,Type ** 到 Type const ** 的转换是被禁止的.此外,不允许将 derived ** 转换为 Base **.
In C++, Type ** to Type const ** conversion is forbidden. Also, conversion from derived ** to Base ** is not allowed.
为什么这些转换是 wtong ?还有其他不能发生指针转换的例子吗?
Why are these conversions wtong ? Are there other examples where pointer to pointer conversion cannot happen ?
有没有办法解决:如何将指向 Type 类型的非常量对象的指针转换为指向 Type 类型的 const 对象的指针code>,因为 Type ** --> Type const ** 不成功?
Is there a way to work around: how to convert a pointer to pointer to a non-const object of type Type to a pointer to pointer to const object of type Type, since Type ** --> Type const ** does not make it ?
推荐答案
Type * to const Type* 是允许的:
Type t;
Type *p = &t;
const Type*q = p;
*p可以通过p修改,但不能通过q修改.
*p can be modified through p but not through q.
如果 Type ** 到 const Type** 转换被允许,我们可能有
If Type ** to const Type** conversion were allowed, we may have
const Type t_const;
Type* p;
Type** ptrtop = &p;
const Type** constp = ptrtop ; // this is not allowed
*constp = t_const; // then p points to t_const, right ?
p->mutate(); // with mutate a mutator,
// that can be called on pointer to non-const p
最后一行可能会改变 const t_const !
The last line may alter const t_const !
derived ** 到 Base ** 的转换,Derived1 和 Derived2 类型派生时会出现问题来自相同的 Base.那么,
For the derived ** to Base ** conversion, problem occurs when Derived1 and Derived2 types derive from same Base. Then,
Derived1 d1;
Derived1* ptrtod1 = &d1;
Derived1** ptrtoptrtod1 = &ptrtod1 ;
Derived2 d2;
Derived2* ptrtod2 = &d2;
Base** ptrtoptrtobase = ptrtoptrtod1 ;
*ptrtoptrtobase = ptrtod2 ;
并且一个 Derived1 * 指向一个 Derived2.
and a Derived1 * points to a Derived2.
将 Type ** 设为指向 const 的指针的正确方法是将其设为 Type const* const*.
Right way to make a Type ** a pointer to pointer to a const is to make it a Type const* const*.
这篇关于C++禁止指针到指针转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++禁止指针到指针转换
基础教程推荐
- CString 到 char* 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
