在运算符重载++,--,+=,-=...

时间:2022-05-05
本文章向大家介绍在运算符重载++,--,+=,-=...,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
 1 //有关运算符重载
 2 //实现一个复数之间的相加
 3 #include<iostream>
 4 using namespace std;
 5 class Complex
 6 {
 7     public:
 8     Complex(double r ,double a);
 9     Complex(){};
10     Complex operator + (const Complex &aa) const ;
11     Complex operator - (const Complex &bb) const ;
12     void fun();
13     private:
14     double real;
15     double imag;
16 };
17  Complex::Complex(double r=0.0 ,double a=0.0):real(r),imag(a){};
18 Complex Complex::operator +(const Complex &aa) const
19 {
20     Complex ans(real+aa.real,imag+aa.imag);
21     //ans.real=real-aa.real;
22     //ans.imag=imag-aa.imag;
23     return ans;
24 };
25 void Complex::fun()
26 {
27     cout<<this->real<<" "<<this->imag<<endl;
28 }
29 Complex Complex::operator -(const Complex &bb) const
30 {
31     return Complex(real-bb.real,imag-bb.imag);
32 }
33 int main()
34 {
35     Complex aa(5,6),bb(7,3);
36     aa=aa+bb;
37     aa.fun();
38     return 0;
39 }