在C ++中,禁止Type **
到Type const **
转换。此外,不允许从derived **
转换为Base **
。
为什么这些转换会重叠?还有其他例子指向指针转换的指针不会发生吗?
有没有办法解决:如何将指向指向类型为Type
的非const对象的指针转换为指向类型为Type
的const对象的指针,因为{{ 1}} - > Type **
没有成功吗?
答案 0 :(得分:5)
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*
。