kir*_*off 3 c++ pointers type-conversion
在C++中,Type **以Type const **转换被禁止.此外,不允许从转换derived **为Base **.
为什么这些转换会重要?还有其他例子指向指针转换的指针不会发生吗?
有没有办法解决:如何将指向指向非const类型对象的指针转换为指向类型的const对象的Type指针Type,因为Type **- > Type const **不成功?
Type *到const Type*被允许:
Type t;
Type *p = &t;
const Type*q = p;
Run Code Online (Sandbox Code Playgroud)
*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
Run Code Online (Sandbox Code Playgroud)
最后一行可能会改变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 ;
Run Code Online (Sandbox Code Playgroud)
并Derived1 *指向一个Derived2.
制作Type **指向const的指针的正确方法是使它成为一个Type const* const*.
| 归档时间: |
|
| 查看次数: |
1015 次 |
| 最近记录: |