运算符重载:
1、外部实现
2、内部实现:外部到内部 ----> 去掉左操作数,由this指针代替
注意:
1、不能改变运算符的优先级
2、不能改变运算符的操作数个数
3、不能自创运算符
4、同一种运算,内部和外部实现只能存在一个
#include <iostream>
using namespace std;
// a+bi 1+2i 复数
class Complex
{
friend Complex operator+(Complex &c1, Complex &c2);
friend Complex operator+(Complex &c1, int num);
public:
Complex(int a = 0, int b = 0)
{
m_a = a;
m_b = b;
}
void show()
{
if (m_b == 0)
cout << m_a << endl;
else if(m_b>0)
cout << m_a << " + " << m_b << "i" << endl;
else
cout << m_a << " - " << m_b*-1 << "i" << endl;
}
Complex operator-(Complex &c2)
{
Complex tmp(m_a - c2.m_a, m_b - c2.m_b);
return tmp;
}
Complex operator -(int num)
{
Complex tmp(m_a - num, m_b);
return tmp;
}
private:
int m_a; // 实部
int m_b; // 虚部
};
Complex operator+(Complex &c1, Complex &c2)
{
Complex tmp(c1.m_a + c2.m_a, c1.m_b + c2.m_b);
return tmp;
}
Complex operator+(Complex &c1, int num)
{
Complex tmp(c1.m_a + num, c1.m_b);
return tmp;
}
int main()
{
Complex c1(1,2), c2(3), c3(1,-1), c4;
c1.show();
c2.show();
c3.show();
c4.show();
// Complex 是自定义类型,编译不知道运算规则
//1、判断运算方式: ===> 做加法运算
//2、调用相关函数进行运算: ====>
// 函数:
// 1、函数名 : operator + 运算符,例如:做加法运算 operator+ 做减法运算: operator-
// 2、函数参数 :参与运算的操作数,从左到右写 : operator+(c1, c2)
// 3、函数的返回值: 根据需要确定 ===> Complex operator+(Complex &c1, Complex &c2)
// 函数找到 ---> 直接调用 找不到:出错 ----> 自己写
c4 = c1 + c2;
c4.show();
Complex c5;
c5 = c1 + 10; // Complex operator+(Complex &c1, int num)
c5.show();
c5 = c1 - c2;
c5.show();
c5 = c1 - 10;
c5.show();
return 0;
}