C ++禁止指针转换指针 [英] C++ forbidden pointer to pointer conversion

查看:114
本文介绍了C ++禁止指针转换指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆