取消引用常量的指针 [英] Dereferencing a pointer to constant

查看:101
本文介绍了取消引用常量的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个称为object的类。

Let's say we have a class called object.

int main(){
    object a;
    const object* b = &a;
    (*b); 
}

问题:
b是指向const的指针,但它是对象指向的实际上不是一个常量对象。我的问题是,当我们取消引用指针 b时,为什么要得到一个常量对象而不是它实际指向的对象是普通的非常量对象。

Question: b is a pointer to const, but the object it is pointing to is actually not a constant object. My question is, when we dereference the pointer "b" why do we get a constant object instead of what it is actually pointing at which is normal non constant object.

推荐答案

因为这就是内置的取消引用运算符 * 在C ++中的工作方式。如果取消引用类型为 T * 的指针,则会得到类型为 T 的左值。在您的情况下, T const对象

Because that's how the built-in dereference operator * works in C++. If you dereference a pointer of type T *, you get an lvalue of type T. In your case T is const object.

都不是 * 运算符,指针本身并不关心(或知道)指针指向的对象是实际上是非恒定的。在C ++语言使用的静态类型化概念中,这是没有其他方法的。

Neither * operator, not the pointer itself cares (or knows) that the object the pointer is pointing to is actually non-constant. It just can't be any other way within the concept of static typing used by C++ language.

const限定的全部目的在于第一个(更深层次的)间接访问级别是为了使您能够创建对对象的限制性访问路径。即通过创建指向const的指针,您会故意并愿意阻止自己(或其他人)修改指针,即使指针不是恒定的。

The whole purpose of const-qualification at the first (and deeper) levels of indirection is to provide you with an ability to create restrictive access paths to objects. I.e. by creating a pointer-to-const you are deliberately and willingly preventing yourself (or someone else) from modifying the pointee, even if the pointee is not constant.

这篇关于取消引用常量的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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