C++ 禁止指针到指针的转换

标签 c++ pointers type-conversion

在 C++ 中,Type **Type const **禁止转换。此外,从 derived ** 转换至 Base **不被允许。

为什么这些转换是 wtong 的?还有其他不能发生指针到指针转换的例子吗?

有没有办法解决:如何将指针转换为指向 Type 类型的非常量对象的指针指向指向类型为 Type 的 const 对象的指针, 自 Type ** --> Type const **做不到?

最佳答案

Type *const Type* 是允许的:

Type t;
Type *p = &t;
const Type*q = p;

*p可以通过p修改,但不能通过q修改。

如果允许从 Type **const Type** 的转换,我们可能有

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 !

对于derived **Base **的转换,Derived1Derived2类型派生时会出现问题来自相同的 Base。然后,

Derived1 d1;
Derived1* ptrtod1 = &d1;
Derived1** ptrtoptrtod1 = &ptrtod1 ;

Derived2 d2;
Derived2* ptrtod2 = &d2;

Base** ptrtoptrtobase = ptrtoptrtod1 ;
*ptrtoptrtobase  = ptrtod2 ;

Derived1 * 指向 Derived2

使 Type ** 成为指向 const 指针的指针的正确方法是使其成为 Type const* const*

关于C++ 禁止指针到指针的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16130900/

相关文章:

c++ - 标准异常层次结构的原因

c++ - cocos2d-x 在 3d 中重复纹理

c - Essential C 书中的 Swap() func 无法编译

二维数组上下文中的 C 指针

c# - 在 C# 中选择搜索结果的类型

json - 将 DataResponse<String> 转换为可用类型

c++ - OpenCV 将有界文本区域复制到新图像

c++ - 为什么 SampleDesc 的质量应该比 Directx11 中的 Msaaquality 小 1?

c - 通过指针访问另一个结构成员

javascript - 不同数据类型的争论