C++--模板遇上运算符重载

时间:2022-02-14 17:20:44
#include <iostream>
using namespace std;

template <typename T>
class Complex
{
friend Complex MySub(Complex& c1,Complex& c2)
{
Complex temp(c1.a-c2.a,c1.b-c2.b);
return temp;
}
friend ostream& operator<<(ostream &out, Complex& c3)
{
out << c3.a << "+" << c3.b << "i" << endl;
return out;
}
public:
Complex(T a,T b)
{
this->a = a;
this->b = b;
}
Complex operator +(Complex &c2)
{
Complex tmp(a+c2.a,b+c2.b);
return tmp;
}
void print()
{
cout << "a " << a << "b" << b << endl;
}
private:
T a;
T b;
};


int main()
{
Complex<int> c1(1,2);
Complex<int> c2(3,4);
Complex<int> c3 = c1 + c2;
cout << c3 << endl;
{
Complex<int> c4=MySub(c1,c2);
cout << c4 << endl;
}
return 0;
}