#include <iostream> using namespace std; template<typename T> class Complex { public : Complex() { } Complex(T a, T b) { this->a = a; this->b = b; } v ...
#include <iostream>
using namespace std;
template<typename T>
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<< <T>(ostream &os, Complex<T> &c);
#if 0
// 這種方式不會報錯,但是另外那種方式一直出錯
friend ostream & operator<<(ostream &os, Complex& c)
{
os << c.a << "+j" << c.b << endl;
return os;
}
#endif
Complex operator+(const Complex<T> &c)
{
return Complex(this->a+c.a, this->b+c.b);
}
private :
T a;
T b;
};
template<typename T>
ostream & operator<<(ostream &os, Complex<T> &c)
{
os << c.a << "+j" << c.b << endl;
return os;
}
int main()
{
Complex<int> c1(10, 20);
c1.printComplex();
Complex<int> c2(1, 2);
c2.printComplex();
Complex<int> c3 = c1+c2;
cout << c3;
return 0;
}
以上代碼出以下錯誤
error: template-id ‘operator<<
苦苦詢問度娘,沒有找到和我同樣錯誤的,經過多方參考,其實只要在前面對友元函數和類進行申明即可
#include <iostream>
using namespace std;
#if 0
如果模板類外實現友元函數,必須在前面對友元函數進行申明,包括類也必須申明
#endif
// 申明,如果不聲明,會一直錯下去
// template<typename T>
// class Complex;
template<typename T>
ostream & operator<<(ostream &os, Complex<T> &c);
template<typename T>
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<< <T>(ostream &os, Complex<T> &c);
#if 0
// 這種方式不會報錯,但是另外那種方式一直出錯
friend ostream & operator<<(ostream &os, Complex& c)
{
os << c.a << "+j" << c.b << endl;
return os;
}
#endif
Complex operator+(const Complex<T> &c)
{
return Complex(this->a+c.a, this->b+c.b);
}
private :
T a;
T b;
};
template<typename T>
ostream & operator<<(ostream &os, Complex<T> &c)
{
os << c.a << "+j" << c.b << endl;
return os;
}
int main()
{
Complex<int> c1(10, 20);
c1.printComplex();
Complex<int> c2(1, 2);
c2.printComplex();
Complex<int> c3 = c1+c2;
cout << c3;
return 0;
}