gpt4 book ai didi

c++ - 在 C++ 中重载运算符时指定 "const"

转载 作者:行者123 更新时间:2023-11-30 01:46:38 25 4
gpt4 key购买 nike

代码:

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”说明符。我对常量引用的理解是,我们不允许更改存储在引用中的值.但在 operator++ 函数内部(第 26-30 行),成员变量“itsVal”递增。这不违反函数定义中的“const”要求吗?

最佳答案

运算符返回对内部参数的引用作为常量引用,这意味着客户端代码无法修改它们从运算符接收到的引用。

另一方面,如果成员函数本身是 const:

const Counter& Counter::operator++() const

那么函数将不允许修改它的任何成员。就目前而言,它可以在返回引用之前进行任何它想要的修改。

关于c++ - 在 C++ 中重载运算符时指定 "const",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32854800/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com