操作符重载
类的所有的成员函数隐藏this指针.
reference:传递者无需知道接收者是以reference形式接受.
复制代码
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99//成员函数操作符重载 inline complex& __doapl(complex *this,const complex&r) { return *this; } inline complex & complex::operator+=(const complex& r) { return _doapl(this,r); } C3+=C2+=C1; //使用者使用连串使用的方式 返回reference &,所以不返回void inline double imag(const complex&x) //传引用比较快 { return x.imag(); } //非成员函数操作符重载.return by value不能返回return by reference,返回的是local object. inline complex operator +(const complex& x,const complex& y) { return complex(real(x)+real(y), //typename()创建临时对象 imag(x)+imag(y)); } inline complex operator +(const complex& x) { return x; } inline complex operator - (const complex &x) { return complex(-real(x),-image(x)); } inline bool operator !=(const complex &x, const complex &y) { return real(x)!=real(y) ||imag(x)!=imag(y); } #include<iostream> inline complex conj(const complex&x) { return complex(real(x),-imag(x)); } ostream & operator<<(ostream &os,const complex&) { return os<<'('<<real(x)<<','<<imag(x)<<')'; } complex c1(2,1); cout<<conj(c1);-->(2,-1) cout<<c1<<conj(c1);-->(2,1)(2,-1) //返回值为ostream class complex { public: complex (double r=0,double i=0) :re(r),im(i) {} complex &operator +=(const complex&); double real() const { return re; } double imag() const { return im; } private://数据放到private里面 double re; double im; friend complex& _doapl(complex *,const complex&); }; #ifndef __COMPLEX__ #define __COMPLEX__ class complex { public: complex(double r=0,double i=0) :re(r),im(i)//初值列 {} complex& operator+=(const complex&); inline double real() const { return re; } inline double imag() const { return im; } private: double re,im; friend complex& __doapl(complex *,const complex&); } #endif inline complex& __doapl(complex *ths,const complex& r)//告诉编译器去inline { ths->re+=r.re; ths->im+=r.im; return *ths; } inline complex& complex::operator +=(const complex& r) { return __doapl(this,r); } inline complex operator + (const complex & x,const complex & y)//return by value { return complex(real(x)+real(y), //typename()创建临时对象 imag(x)+imag(y)); } #include <iosteam> inline ostream& operator <<(ostream& os,const complex& x) { return os<<'('<<real(x)<<','<<imag(x)<<')'; }
最后
以上就是机灵眼神最近收集整理的关于C++操作符重载的全部内容,更多相关C++操作符重载内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复