在 c++ 中重载运算符时指定"const"
Specifying "const" when overloading operators in c++
代码:
4: typedef unsigned short USHORT;
5: #include <iostream.h>
6:
7: class Counter
8: {
9: public:
10: Counter();
11: ~Counter(){}
12: USHORT GetItsVal()const { return itsVal; }
13: void SetItsVal(USHORT x) {itsVal = x; }
14: void Increment() { ++itsVal; }
15: const Counter& operator++ ();
16:
17: private:
18: USHORT itsVal;
19:
20: };
21:
22: Counter::Counter():
23: itsVal(0)
24: {};
25:
26: const Counter& Counter::operator++()
27: {
28: ++itsVal;
29: return *this;
30: }
31:
32: int main()
33: {
34: Counter i;
35: cout << "The value of i is " << i.GetItsVal() << endl;
36: i.Increment();
37: cout << "The value of i is " << i.GetItsVal() << endl;
38: ++i;
39: cout << "The value of i is " << i.GetItsVal() << endl;
40: Counter a = ++i;
41: cout << "The value of a: " << a.GetItsVal();
42: cout << " and i: " << i.GetItsVal() << endl;
48: return 0;
49: }
我正在研究C++中的重载运算符,无法理解第26行中的"const"说明符。我理解常量引用的方式是,我们不允许更改存储在引用中的值。但在运算符++函数(第26-30行(中,成员变量"itsVal"会递增。这是否违反了函数定义中的"const"要求?
运算符将返回对内部参数的引用作为常量引用,这意味着客户端代码不能修改从运算符接收的引用。
另一方面,如果成员函数本身是常量:
const Counter& Counter::operator++() const
则该函数将不被允许修改其任何成员。目前,它可以在返回引用之前进行任何修改。
相关文章:
- 在运算符重载定义中使用成员函数(const错误)
- 不允许运算符 const 参数调用 const 成员函数
- C++概念assignable_from不接受 const&-return 运算符=
- 有人可以用"显式运算符 const GUID_t&() const"来解释成员函数的函数吗?
- 关于重载 -> 运算符中 const 关键字的特定位置的问题
- 类型"int"和"const char [15]"到二进制"运算符<<"的无效操作数^
- 在函数中使用运算符重载,在 c++ 中使用 const 类型输入参数
- 为什么我需要三个嵌套的大括号来调用赋值运算符,将const引用到二维数组
- 为什么 std::basic_ostream::运算符<<不符合 CONST 资格?
- 在运算符重载中使用带有 const 引用的 friend 函数
- STL按客户"<"运算符对向量进行排序。为什么要将"<"运算符定义为 const?
- 如何在 std::map<const int、int> C++ 中重载插入运算符>>?
- 错误:二进制">>":未找到采用类型为"const char [1] 的右操作数的运算符
- 为什么重载运算符>在参数声明 const 时不起作用?
- 我收到一个错误无效的操作数,类型为 const char [42] 和二进制"运算符+"的双倍数
- 错误:C2679 二进制"==":未找到采用类型 'const std::string' 的右侧操作数的运算符(或者没有可接受的转换)
- 重载 * 运算符时不使用 const 的影响
- Const 仍然允许在运算符函数 c++ 下进行更改
- const std::function 包装一个非 const 运算符() / 可变 lambda
- 成员函数中的Const运算符(为什么可以分为两个不同的部分)