#include
using namespace std;
template
class Complex
{
public :
Complex()
{
}
Complex(T a, T b)
{
this->a = a;
this->b = b;
}
void printComplex()
{
cout << a << "+j" << b << endl;
}
friend ostream & operator<< (ostream &os, Complex &c);
#if 0
// 这种方式不会报错,但是另外那种方式一直出错
friend ostream & operator<<(ostream &os, Complex& c)
{
os << c.a << "+j" << c.b << endl;
return os;
}
#endif
Complex operator+(const Complex &c)
{
return Complex(this->a+c.a, this->b+c.b);
}
private :
T a;
T b;
};
template
ostream & operator<<(ostream &os, Complex &c)
{
os << c.a << "+j" << c.b << endl;
return os;
}
int main()
{
Complex c1(10, 20);
c1.printComplex();
Complex c2(1, 2);
c2.printComplex();
Complex c3 = c1+c2;
cout << c3;
return 0;
}
以上代码出以下错误
error: template-id ‘operator<< ’ for ‘std::ostream& operator<<(std::ostream&, Complex &)’ does not match any template declaration
苦苦询问度娘,没有找到和我同样错误的,经过多方参考,其实只要在前面对友元函数和类进行申明即可
#include
using namespace std;
#if 0
如果模板类外实现友元函数,必须在前面对友元函数进行申明,包括类也必须申明
#endif
// 申明,如果不声明,会一直错下去
// template
// class Complex;
template
ostream & operator<<(ostream &os, Complex &c);
template
class Complex
{
public :
Complex()
{
}
Complex(T a, T b)
{
this->a = a;
this->b = b;
}
void printComplex()
{
cout << a << "+j" << b << endl;
}
friend ostream & operator<< (ostream &os, Complex &c);
#if 0
// 这种方式不会报错,但是另外那种方式一直出错
friend ostream & operator<<(ostream &os, Complex& c)
{
os << c.a << "+j" << c.b << endl;
return os;
}
#endif
Complex operator+(const Complex &c)
{
return Complex(this->a+c.a, this->b+c.b);
}
private :
T a;
T b;
};
template
ostream & operator<<(ostream &os, Complex &c)
{
os << c.a << "+j" << c.b << endl;
return os;
}
int main()
{
Complex c1(10, 20);
c1.printComplex();
Complex c2(1, 2);
c2.printComplex();
Complex c3 = c1+c2;
cout << c3;
return 0;
}