c++友元重载运算符的模板类实现问题
知道把友元函数体放到类声明内部,使其跟着类的实例化一同实例化,可以使友元重载运算符函数运行成功。但是如果将重载运算符的定义分开书写。则会出错。求解。#include <iostream>
using namespace std;
//发现重载运算符函数写在定义友函数时没有,但分离便有错值得注意
//有空找原因
template <class T>
class Complex
{
public:
Complex(){real=0;imag=0;}
Complex(T r,T i):real(r),imag(i){}
Complex(double r){real=r;imag=0;}
friend Complex operator +(Complex c1,Complex c2)
{
return Complex(c1.real+c2.real,c1.imag+c2.imag);
}
friend Complex operator -(Complex c1,Complex c2)
{
return Complex(c1.real-c2.real,c1.imag-c2.imag);
}
friend Complex operator *(Complex c1,Complex c2)
{
return Complex(c1.real*c2.real-c1.imag*c2.imag,c1.real*c2.imag+c1.imag*c2.real);
}
friend Complex operator /(Complex c1,Complex c2)
{
Complex c3;
c3.real=(c1.real*c2.real-c1.imag*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag);
c3.imag=(c1.real*c2.imag+c1.imag*c2.real)/(c2.real*c2.real+c2.imag*c2.imag);
return c3;
}
friend istream&operator>>(istream&input,Complex <T>&obj)
{
input>>obj.real>>obj.imag;
return input;
}
friend ostream& operator<<(ostream &output,Complex<T> &obj)
{
output<<"("<<obj.real<<"+"<<obj.imag<<"i)";
return output;
}
private:
T real;
T imag;
};
int main()
{
Complex<double> obj_1(1,2);
Complex<double> obj_2(1,2);
Complex<double> obj_3;
obj_3=obj_1+obj_2;
cout<<"obj_3=obj_1+obj2=";cout<<obj_3<<endl;
obj_3=obj_1-obj_2;
cout<<"obj_3=obj_1-obj2=";cout<<obj_3<<endl;
obj_3=obj_1*obj_2;
cout<<"obj_3=obj_1*obj2=";cout<<obj_3<<endl;
obj_3=obj_1/obj_2;
cout<<"obj_3=obj_1/obj2=";cout<<obj_3<<endl;
obj_3=obj_1+2.5;
cout<<"obj_3=obj_1+2.5=";cout<<obj_3<<endl;
obj_3=2.5+obj_1;
cout<<"obj_3=2.5+obj_1=";cout<<obj_3<<endl;
return 0;
}