简体   繁体   English

在C ++中重载运算符时指定“ const”

[英]Specifying “const” when overloading operators in c++

Code: 码:

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: }

I'm studying overloading operators in C++ and can't wrap my head around the "const" specifier in line 26. The way I understood constant reference is that we are not allowed to change the value that is stored in the reference. 我正在研究C ++中的重载运算符,因此无法绕过第26行中的“ const”说明符。我理解常量引用的方式是不允许我们更改存储在引用中的值。 But inside the operator++ function (lines 26-30), the member variable "itsVal" is incremented. 但是在operator ++函数(第26-30行)中,成员变量“ itsVal”增加了。 Doesn't this violate the "const" requirement in the function's definition? 这不违反函数定义中的“ const”要求吗?

The operator is returning a reference to an internal parameter as a const reference, which means that client code can not modify the reference they receive from the operator. 操作员将返回对内部参数的引用作为const引用,这意味着客户端代码无法修改从操作员那里收到的引用。

If, on the other hand the member function itself was const: 另一方面,如果成员函数本身是const:

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

then the function would not be allowed to modify any of its members. 那么该函数将不允许修改其任何成员。 As it stands it can do any modification it wants before returning the reference. 就目前而言,它可以在返回引用之前进行所需的任何修改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM