0条评论
还没有人评论过~
#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; }