我在 c++ 代码的这一部分中找不到第二个常量实用程序,有人可以解释一下吗?

I can't find the utility of the second const in this part of c++ code, can someone explain please?

本文关键字:解释 一下 代码 c++ 一部分 实用程序 常量 第二个 找不到 我在      更新时间:2023-10-16

表示成员函数中的this指针为const。换句话说,调用不会修改对象。(它返回的任何引用/指针也将是const)。

这种语法适用于类内部的方法。标记为const(代码中的第二个const)的方法不能修改对象的属性,只能读取。如果将对象实例化为const, Const方法是唯一可调用的方法。情况:

class A {
public:
  void put(int v) {
    var = v;
  }
  int read() const {
    return var;
  }
private:
  int var;
}
int main() {
  A obj;
  obj.put(3);
  const A obj2 = obj;
  obj2.read(); // OK, returns 3;
  obj2.put(4); // Compile time error!
}

Michael的回答几乎涵盖了所有内容,但还有其他一些方面:

  • 只允许在const方法中调用const方法。
  • 可以更改成员,如果你声明他们为可变的。
  • 您将无法更改类的任何其他成员。

只有成员函数可以const限定,非成员函数不能。对于 c++ 也是如此。C没有成员函数的概念,因此它们不能。