前言
递增运算符分为前置和后置两种,下面的代码块中分别展示了两种递增运算符。其中,等式1展示了前置递增运算符,变量a首先进行递增操作,其值变为1,再赋值给变量b,此时b的值为1。等式2展示了后置运算符,变量a在递增前值为1,先复制给变量b,b的值此时为1,再对a进行递增操作,将a的值增加到2。
1 2 3 4
| int a = 0; int b = 1; int b = ++a; # 等式1 int b = a++; # 等式2
|
重载递增运算符
创建自己的整形类
为了重载递增运算符,我们需要创建一个自己的整形类MyInteger,其包含一个int类型的成员变量num。
1 2 3 4 5 6 7 8 9 10 11 12
| class MyInteger {
public: MyInteger() { num = 0; }
private: int num; };
|
重载前置递增运算符
前置递增运算符先进行递增操作,再进行赋值操作。其递增后的结果需要返回给函数,因此应当将返回值的类型设置为引用类型,即MyInteger&,返回的是当前对象。重载的前置递增运算符如下:
1 2 3 4 5
| MyInteger& operator++() { num++; return *this; }
|
重载后置递增运算符
后置递增运算符先进行赋值操作,再进行递增操作。其返回的是递增前的结果,因此应当拷贝递增前的对象,再对原对象进行递增操作,将拷贝结果作为函数返回值。重载的后置递增运算符如下:
1 2 3 4 5 6
| MyInteger operator++(int) { MyInteger temp = *this; num++; return temp; }
|
重载输出运算符
为了验证重载后的递增运算符的有效性,我们重载输出运算符,以输出实验结果。
1 2 3 4 5
| ostream& operator<<(ostream& cout, MyInteger myInt) { cout << myInt.num; return cout; }
|
实验结果
首先使用如下代码块测试前置递增运算符的实验结果:
1 2 3 4 5 6
| void test1() { MyInteger myInt; cout << ++myInt << endl; cout << myInt << endl; }
|
输出结果如下:
使用如下代码测试后置递增运算符的实验结果:
1 2 3 4 5 6
| void test2() { MyInteger myInt; cout << myInt++ << endl; cout << myInt << endl; }
|
输出结果如下:
实验结果表明重载成功。
完整代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| #include <iostream> #include <string> using namespace std;
class MyInteger {
friend ostream& operator<<(ostream& cout, MyInteger myInt);
public: MyInteger() { num = 0; }
MyInteger& operator++() { ++num; return *this; }
MyInteger operator++(int) { MyInteger temp = *this; num++; return temp; }
private: int num; };
ostream& operator<<(ostream& cout, MyInteger myInt) { cout << myInt.num; return cout; }
void test1() { MyInteger myInt; cout << ++myInt << endl; cout << myInt << endl; }
void test2() { MyInteger myInt; cout << myInt++ << endl; cout << myInt << endl; }
int main() { test2(); system("pause");
return 0; }
|