在 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 **
的转换,Derived1
和Derived2
类型派生时会出现问题来自相同的 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/