在 C++ 中,Type **禁止Type const **转换。此外,不允许从derived **to转换。Base **
为什么这些转换 wtong ?还有其他不能发生指针转换的例子吗?
有没有办法解决:如何将指向非 const 类型对象指针的指针转换为指向 const 类型对象Type指针的指针Type,因为Type **-->Type const **没有做到这一点?
在 C++ 中,Type **禁止Type const **转换。此外,不允许从derived **to转换。Base **
为什么这些转换 wtong ?还有其他不能发生指针转换的例子吗?
有没有办法解决:如何将指向非 const 类型对象指针的指针转换为指向 const 类型对象Type指针的指针Type,因为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 **toBase **转换,当Derived1和Derived2类型派生自相同时会出现问题Base。然后,
Derived1 d1;
Derived1* ptrtod1 = &d1;
Derived1** ptrtoptrtod1 = &ptrtod1 ;
Derived2 d2;
Derived2* ptrtod2 = &d2;
Base** ptrtoptrtobase = ptrtoptrtod1 ;
*ptrtoptrtobase = ptrtod2 ;
并且 aDerived1 *指向 a Derived2。
Type **制作指向 const 指针的指针的正确方法是将其设为Type const* const*.