#include <iostream>
using namespace std;
class Complex
{
friend Complex operator+(Complex &c1, Complex &c2);
private:
int a;
int b;
public:
Complex(int a = 0, int b = 0)
{
this->a = a;
this->b = b;
}
void printCom()
{
cout << a << "+" << b << "i" << endl;
}
//成员函数 法 实现 - 运算符重载
Complex operator-(Complex &c2)
{
Complex tmp(this->a-c2.a,this->b-c2.b);
return tmp;
}
};
//全局函数法 实现 + 运算符重载
Complex operator+(Complex &c1, Complex &c2)
{
Complex tmp(c1.a+c2.a, c1.b+c2.b);
return tmp;
}
/*
全局函数、类成员函数方法实现运算符重载步骤:
1)要承认操作符重载是一个函数,写出函数名称
2)根据操作数,写出函数参数
3)根据业务,完善函数返回值(看函数是返回引用 还是指针 元素),及实现函数业务
*/
int main()
{
Complex c1(1, 2), c2(3,4);
//1 全局函数法 实现 + 运算符重载
//Complex operator+(Complex &c1, Complex &c2);
Complex c3 = c1 + c2;
c3.printCom();
//2 成员函数 法 实现 + 运算符重载
//c1.operator+(this,c2);
//
//Complex operator-(Complex &c2);
Complex c4 = c1 - c2;
c4.printCom();
return 0;
}
P210_成员函数和友元函数完成二元运算符的两种方法
猜你喜欢
转载自blog.csdn.net/weixin_41983807/article/details/87799237
今日推荐
周排行