C ++禁止指针转换指针

时间:2013-04-21 12:04:37

标签: c++ pointers type-conversion

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

为什么这些转换会重叠?还有其他例子指向指针转换的指针不会发生吗?

有没有办法解决:如何将指向指向类型为Type的非const对象的指针转换为指向类型为Type的const对象的指针,因为{{ 1}} - > Type **没有成功吗?

1 个答案:

答案 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 **转换,如果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*