c++ -> 运算符重载(+ && -)
程序员文章站
2024-02-28 19:47:40
...
#include <iostream>
using namespace std;
class Complex
{
private:
int a;
int b;
friend Complex myAdd(Complex &c1, Complex &c2);
friend Complex operator+(Complex &c1, Complex &c2);
friend Complex myMinus(Complex &c1, Complex &c2);
friend Complex operator-(Complex &c1, Complex &c2);
public:
Complex(int a = 0, int b = 0)
{
this->a = a;
this->b = b;
}
void printCom()
{
cout << a << "+" << b << "i" << endl;
}
};
//定义全局函数
Complex myAdd(Complex &c1, Complex &c2)
{
Complex tmp(c1.a + c2.a, c1.b + c2.b);
return tmp;
}
Complex operator+(Complex &c1, Complex &c2)
{
Complex tmp(c1.a + c2.a, c1.b + c2.b);
return tmp;
}
//实现减法的运算符重载
Complex myMinus(Complex &c1, Complex &c2)
{
Complex tmp(c1.a - c2.a, c1.b - c2.b);
return tmp;
}
Complex operator-(Complex &c1, Complex &c2)
{
Complex tmp(c1.a - c2.a, c1.b - c2.b);
return tmp;
}
// + 号测试函数
int main01()
{
Complex c1(1, 2), c2(3, 4);
//方法1
Complex c4 = myAdd(c1, c2);
c4.printCom();
//方法2
Complex c3 = operator+(c1, c2);
c3.printCom();
//方法3
Complex c5 = c1 + c2;
c5.printCom();
return 0;
}
// - 号测试函数
int main()
{
Complex c1(1, 2), c2(3, 4);
//方法1
Complex c4 = myMinus(c1, c2);
c4.printCom();
//方法2
Complex c3 = operator-(c1, c2);
c3.printCom();
//方法3
Complex c5 = c1 - c2;
c5.printCom();
return 0;
}