运算符重载

来源:互联网 发布:石头纸 知乎 编辑:程序博客网 时间:2024/04/30 05:37
#include <iostream>
using namespace std;

//a+bi


class  Complex
{
public:
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 ComAdd(Complex &c1, Complex &c2)
{
Complex tmp;
tmp.a = c1.a + c2.a;
tmp.b = c1.b + c2.b;
return tmp;
}

Complex operator+(Complex &c1, Complex &c2)
{
Complex tmp;
tmp.a = c1.a + c2.a;
tmp.b = c1.b + c2.b;
return tmp;
}


void main()
{
Complex c1(1, 2), c2(3, 4), c4;
c4 = ComAdd(c1, c2);
c4.printCom();
Complex c3 = c1 + c2;
c3.printCom();
system("pause");

}


运行结果:


0 0
原创粉丝点击