运算符重载

发布时间 2023-08-01 17:47:53作者: hello睡不醒

运算符重载:对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型

1.加号运算符重载

 2.左移运算符重载

一般输出时 cout<<p.m_A<<" "<<p.m_B<<endl; 但是现在想用<<直接输出p,(直接输出类类型的p, cout<<p<<endl; )该怎么办呢?

利用成员函数重载  左移运算符       p.operator<<(cout)  简化版本: p<<cout ;

不会利用成员函数重载<<运算符,因为无法实现cout在左侧;so用全局函数。

cout是在ostream类下的一个对象,且只有唯一一个,所以要加&;

 没完呢 !!!此时还不能再追加一个东西如 cout<<p<<endl; 因为cout<<p;之后返回的不是cout,那怎么让cout调用<<完还是cout呢?(链式编程思想)

接下来:

  3.递增运算符重载

 

 1 #include<iostream>
 2 using namespace std;
 3 //前置递增返回引用,后置递增返回值 
 4 class HH
 5 {
 6 public:
 7     int m_num;
 8     HH()
 9     {
10         m_num=0;
11     }
12     //前置++
13     HH& operator++()
14     {
15         //先++
16         m_num+=4;
17         //再返回
18         return *this; 
19     }
20     //后置++
21     HH operator++(int)//int是占位参数,防止与前面的一样
22     {
23         //先记录当前值
24         HH temp=*this;//错误样例:HH temp=m_B; 
25         //再++
26         m_num+=3; 
27         //最后返回记录值
28         return temp; 
29      } 
30 };
31 
32 //左移运算符重载
33 ostream& operator<<(ostream& cout,HH myint)
34 {
35     cout<<myint.m_num;
36     return cout;
37  } 
38 void test01()
39 {
40     HH p;
41     cout<<++p<<endl;
42     cout<<p++<<endl;
43 }
44 int main()
45 {
46     test01();
47  }