C ++禁止指针转换指针 [英] C++ forbidden pointer to pointer conversion
问题描述
在C ++中,键入**
至类型const **
转换被禁止。此外,不允许从派生**
到 Base **
的转换。
In C++, Type **
to Type const **
conversion is forbidden. Also, conversion from derived **
to Base **
is not allowed.
为什么这些转换很重要?还有其他的例子,指针指针转换不能发生吗?
Why are these conversions wtong ? Are there other examples where pointer to pointer conversion cannot happen ?
有一种方法来解决:如何将指针转换为非const类型的对象键入
到
类型类型的const对象的指针指针,因为
键入**
- > 类型const **
不会吗?
Is there a way to work around: how to convert a pointer to pointer to a non-const object of type Type
to a pointer to pointer to const object of type Type
, since Type **
--> Type const **
does not make it ?
推荐答案
类型*
到 const类型*
是允许的:
Type t;
Type *p = &t;
const Type*q = p;
* p
c $ c> p 但不通过 q
。
*p
can be modified through p
but not through q
.
c>输入** 到 const类型**
转换被允许,我们可能有
If Type **
to const Type**
conversion were allowed, we may have
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
!
到
基本**
转换,当 Derived1
和 Derived2
类型派生自相同的 Base
。然后,
For the derived **
to Base **
conversion, problem occurs when Derived1
and Derived2
types derive from same Base
. Then,
Derived1 d1;
Derived1* ptrtod1 = &d1;
Derived1** ptrtoptrtod1 = &ptrtod1 ;
Derived2 d2;
Derived2* ptrtod2 = &d2;
Base** ptrtoptrtobase = ptrtoptrtod1 ;
*ptrtoptrtobase = ptrtod2 ;
和 Derived1 *
code> Derived2 。
and a Derived1 *
points to a Derived2
.
正确的方法来创建类型**
指向const的指针是使它成为一个类型const * const *
。
Right way to make a Type **
a pointer to pointer to a const is to make it a Type const* const*
.
这篇关于C ++禁止指针转换指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!