# 成员函数和友元函数 完成二元和一元运算符重载（进阶1）

#include <iostream>
using namespace std;

class Complex{//复数类
private:
int a;
int b;
friend Complex operator + (Complex &, Complex &);//注意声明友元函数
public:
Complex(int a = 0, int b = 0){
this->a = a;
this->b = b;
}
void print(){
cout << "a: " << a  << " " << "b: " << b << endl;
}
};

Complex operator + (Complex &a1, Complex &a2){
Complex tmp(a1.a + a2.a, a1.b + a2.b);
return tmp;
}

int main()
{
Complex c1(1, 2), c2(3, 4), c3;
c3 = c1 + c2;
c3.print();
return 0;
}

#include <iostream>
using namespace std;

class Complex{//复数类
private:
int a;
int b;
public:
Complex(int a = 0, int b = 0){
this->a = a;
this->b = b;
}
void print(){
cout << "a: " << a  << " " << "b: " << b << endl;
}
Complex operator - (Complex &a2){
Complex tmp(this->a - a2.a, this->b - a2.b);
return tmp;
}
};

int main()
{
Complex c1(1, 2), c2(3, 4), c3;
c3 = c1 - c2;
c3.print();
c3 = c2 - c1;
c3.print();
return 0;
}


#include <iostream>
using namespace std;

class Complex{//复数类
private:
int a;
int b;
friend Complex operator ++ (Complex &);
friend Complex operator ++ (Complex &, int);
public:
Complex(int a = 0, int b = 0){
this->a = a;
this->b = b;
}
void print(){
cout << "a: " << a  << " " << "b: " << b << endl;
}
Complex operator -- (){ //前置--操作符，成员函数方法实现
this->a --;
this->b --;
return (*this);
}
Complex operator --(int){ //后置--操作符，成员函数方法实现
Complex tmp = (*this);
this->a --;
this->b --;
return tmp;
}
};

Complex operator ++ (Complex &A){ //前置++操作符，用全局函数实现
A.a ++;
A.b ++;
return A;
}

Complex operator ++ (Complex &A, int){//后置++操作符，全局函数实现     加一个占位符跟前置加以区分
Complex tmp = A;
A.a ++;
A.b ++;
return tmp;
}

int main()
{
Complex c1(1, 2);

//前置++操作符，用全局函数实现
++c1;          //Complex c = operator ++ (c1);
c1.print();

//前置--操作符，成员函数方法实现
--c1;          //Complex c = c1.operator -- (&c1)
c1.print();

//后置++操作符，全局函数实现
c1++;          //Complex c = operator ++ (c1, 0);
c1.print();

//后置--操作符，成员函数方法实现
c1--;          //Complex c = c1.operator -- (0);
c1.print();

return 0;
}


#### 运算符重载函数作为类成员函数与友元函数的区别

2016-03-16 10:49:32

#### 将重载运算符定义为成员函数还是普通的非成员函数

2016-10-25 12:17:02

#### 关于C++成员函数和运算符的重载

2016-11-10 19:36:46

#### C++运算符重载（友元函数方式）

2015-07-10 11:27:53

#### 为什么operator<<>>运算符重载一定要为友元函数呢？

2015-06-11 21:01:55

#### 【C++ primer在练习中体悟】 C++中二元运算符重载需要使用friend的原因

2016-11-28 20:58:51

#### 解决：操作符重载， 二元运算符的参数之一必须是包含类型

2011-12-08 19:50:18

#### 运算符-重载为成员函数 和友元函数的区别.

2008-11-12 12:29:00

#### 【C++】成员函数重载二元和一元运算符

2017-09-22 09:37:28

#### C++友元函数以及运算符重载

2014-03-29 09:50:00