'const'方法可以改变什么? [英] What can a 'const' method change?

查看:79
本文介绍了'const'方法可以改变什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++方法允许使用 const 限定符表示该方法未更改对象。但是,这是什么意思?例如。如果实例变量是指针,是否意味着指针没有改变,或者指针所指向的内存没有改变?

C++ methods allow a const qualifier to indicate that the object is not changed by the method. But what does that mean? Eg. if the instance variables are pointers, does it mean that the pointers are not changed, or also that the memory to which they point is not changed?

具体来说,这是一个最小示例类

Concretely, here is a minimal example class

class myclass {
  int * data;

  myclass() {
    data = new int[10];
  }

  ~myclass() {
    delete [] data;
  }

  void set(const int index) const {
    data[index] = 1;
  }
};

set 方法是否符合 const ?它不会更改成员变量 data ,但确实会更改数组的内容。

Does the method set correctly qualify as const? It does not change the member variable data, but it sure does change the content of the array.

推荐答案

大多数来说,这意味着 this 的类型是const内部的 const T * 成员函数,其中 T 是您的类,而在非限定函数中,成员函数是 T *

Most succinctly, it means that the type of this is const T * inside const member functions, where T is your class, while in unqualified functions it is T *.

您的方法 set 不会更改 data ,因此可以将其限定为const 。换句话说, myclass :: data 作为 this-> data 访问,其类型为 int * const

Your method set does not change data, so it can be qualified as const. In other words, myclass::data is accessed as this->data and is of type int * const.

这篇关于'const'方法可以改变什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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