C++中类成员函数声明末尾的const是什么意思?
大家好!我刚开始学习C++不久,遇到了一种完全无法理解的语法。在代码中看到类方法的声明,参数列表后面有关键字`const`。例如:
```cpp
class MyClass {
public:
int getValue() const; // 这个const是什么意思?
void setValue(int v);
};
```
我知道`const`放在变量类型前使其不可变(例如`const int x = 5;`)。但`const`放在函数声明末尾是做什么的?我尝试编写这样一个方法,但当我在其中试图修改类的字段时,编译器报错了。为什么?
以下是我的无法编译的代码:
```cpp
class Counter {
private:
int count = 0;
public:
int getCount() const {
count = 10; // 错误:不能在const函数中修改类成员
return count;
}
};
```
请解释一下,这样的`const`有什么用?什么时候应该使用它,什么时候不应该?以及这与const对象的工作有什么关系?