在C++中,`const`关键字可以加在函数名的前后,但它们的含义不同,用法也不同。下面详细介绍两种用法及其区别。
### `const` 加在函数名前
将 `const` 加在函数名前,表示函数的返回值是 `const` 类型。这意味着返回的值不能被修改。例如:
```cpp
class MyClass {
public:
const int getValue() {
return 42;
}
};
```
在上面的例子中,`getValue` 函数返回一个 `const int` 类型的值。调用者不能修改这个返回值。例如,下面的代码是错误的:
```cpp
MyClass obj;
int& ref = obj.getValue(); // 错误,不能绑定到 const int
```
### `const` 加在函数名后
将 `const` 加在函数名后,表示该成员函数是一个 `const` 成员函数。这意味着该函数不能修改类的任何非 `mutable` 成员变量,并且不能调用任何非 `const` 成员函数。例如:
```cpp
class MyClass {
private:
int value;
public:
MyClass(int v) : value(v) {}
int getValue() const {
return value;
}
void setValue(int v) {
value = v;
}
};
```
在上面的例子中,`getValue` 函数是一个 `const` 成员函数,保证了它不会修改 `MyClass` 的成员变量。这样就可以在一个 `const` 对象上调用这个函数:
```cpp
const MyClass obj(42);
int val = obj.getValue(); // 可以调用,因为 getValue 是 const 成员函数
// obj.setValue(10); // 错误,不能在 const 对象上调用非 const 成员函数
```
### 区别总结
- **`const` 加在函数名前**:表示返回的值是 `const` 类型,不能被修改。
- **`const` 加在函数名后**:表示该成员函数不会修改类的成员变量,可以在 `const` 对象上调用。
### 示例代码
为了更清晰地理解,我们来看一个综合的示例:
```cpp
class Example {
private:
int value;
public:
Example(int v) : value(v) {}
// 返回一个 const 值
const int getConstValue() {
return value;
}
// 返回一个普通值
int getValue() {
return value;
}
// const 成员函数
int getConstMemberValue() const {
return value;
}
// 非 const 成员函数
void setValue(int v) {
value = v;
}
};
int main() {
Example obj(42);
const Example constObj(42);
int val1 = obj.getConstValue(); // 正常调用
int val2 = obj.getValue(); // 正常调用
int val3 = obj.getConstMemberValue(); // 正常调用
int val4 = constObj.getConstMemberValue(); // 正常调用
// int val5 = constObj.getValue(); // 错误,不能在 const 对象上调用非 const 成员函数
return 0;
}
```
在这个示例中,我们展示了如何在不同情况下使用 `const` 关键字,并且明确了其在函数名前后使用的不同含义。