递增运算符重载(3)

作用:通过重载递增运算符,实现自己的整型数据

 (1)自定义整型数据实现

 1 #include <iostream>
 2 using namespace std;
 3 
 4 class MyInteger
 5 {
 6     friend ostream& operator<<(ostream &cout, MyInteger myint);
 7 public:
 8     MyInteger()
 9     {
10         m_num = 0;
11     }
12 
13 private:
14     int m_num;
15 };
16 
17 //因为cout在左边,所以只能写在全局函数
18 //重载左移运算符<<
19 ostream& operator<<(ostream &cout, MyInteger myint)
20 {
21     cout << myint.m_num;
22     return cout;
23 }
24 
25 void test_01(void)
26 {
27     MyInteger myint;
28 
29     cout << myint << endl;
30 }
31 
32 int main(void)
33 {
34     test_01();
35 
36     system("pause");
37     return 0;
38 }

(2)实现自定义整型数据的自增运算

注意事项:

<1>返回返回引用的区别

 1 //重载前置++运算符
 2 MyInteger& operator++()//返回对象引用,可以实现 ++(++myint),本质就是对一个地址重复操作
 3 {
 4    m_num++;
 5    return *this;
 6  }
 7 
 8 //MyInteger operator++()//返回值,首先运算(++myint)=1,当运算++(++myint)=1,因为操作的不是地址,每次运算取的都是myint值
 9 //{
10 //    m_num++;
11 //    return *this;
12 //}

<2>前置递增和后置递增重载函数的写法和区别:前置递增返回引用,后置递增返回值

 1 //重载后置++运算符
 2     //void operator++(int) int代表占位参数,可以用于区分前置和后置递增
 3     MyInteger operator++(int)//返回值
 4     {
 5         //先记录当时结果
 6         MyInteger temp = *this;
 7         
 8         //后递增
 9         m_num++;
10 
11         //返回记录的结果
12         return temp;
13     }

代码演示:

 1 #include <iostream>
 2 using namespace std;
 3 
 4 class MyInteger
 5 {
 6     friend ostream& operator<<(ostream &cout, MyInteger myint);
 7 public:
 8     MyInteger()
 9     {
10         m_num = 0;
11     }
12 
13     //重载前置++运算符
14     MyInteger& operator++()//返回对象引用,可以实现 ++(++myint),本质就是对一个地址重复操作
15     {
16         m_num++;
17         return *this;
18     }
19 
20     //MyInteger operator++()//返回值,首先运算(++myint)=1,当运算++(++myint)=1,因为操作的不是地址,而是每次取的myint值
21     //{
22     //    m_num++;
23     //    return *this;
24     //}
25 
26     //重载后置++运算符
27     //void operator++(int) int代表占位参数,可以用于区分前置和后置递增
28     MyInteger operator++(int)//返回值
29     {
30         //先记录当时结果
31         MyInteger temp = *this;
32         
33         //后递增
34         m_num++;
35 
36         //返回记录的结果
37         return temp;
38     }
39 
40 private:
41     int m_num;
42 };
43 
44 //因为cout在左边,所以只能写在全局函数
45 //重载左移运算符<<
46 ostream& operator<<(ostream &cout, MyInteger myint)
47 {
48     cout << myint.m_num;
49     return cout;
50 }
51 
52 void test_01(void)
53 {
54     MyInteger myint;
55 
56     cout << ++myint << endl;
57 }
58 
59 void test_02(void)
60 {
61     MyInteger myint;
62 
63     cout << myint++ << endl;
64 }
65 
66 int main(void)
67 {
68     test_01();
69     test_02();
70 
71     system("pause");
72     return 0;
73 }

 

posted @ 2020-04-23 21:53  坦率  阅读(375)  评论(0)    收藏  举报