1,根据情况2,绑定模板友元函数。 template<class T> class CTest; template <class T> ostream & operator<<(ostream &os,const CTest<T>& rhs); template<class T> class CTest { public: CTest(const T& val): _item(val){} ~CTest(void){} friend ostream & operator<< <T>(ostream & os,const CTest<T>&rhs); // care <T> private: T _item; }; template <class T> ostream & operator<<(ostream &os,const CTest<T>& rhs) { os<<"this is CTest:"<<rhs._item<<endl; return os; } 2.根据情况3,用非绑定形式的模板函数 template<class T> class CTest { public: CTest(const T& val): _item(val){} ~Ctest(void){} template<class U> friend ostream & operator<<(ostream & os,const CTest<U>&rhs); private: T _item; }; template <class T> ostream & operator<<(ostream &os,const CTest<T>& rhs) { os<<"this is CTest:"<<rhs._item<<endl; return os; } 上面两种改法都在gcc上面编译通过 // 另一个实例 //----------------------------------------- template<class Type> class Matrix; // 友元类forward declaration template<class Type> ostream &operator << ( ostream &os, Matrix<Type> &m ); template<class Type> Matrix<Type> &operator + ( Matrix<Type> &m1, Matrix<Type> &m2 ); //----------------------------------------- template<class elemType = int> class element{ public: // .... friend class Matrix<elemType>; friend Matrix<elemType> &operator + <elemType>( Matrix<elemType> &m1, Matrix<elemType> &m2 );// care <elemType>, the same as follows friend ostream &operator << <elemType>( ostream &os, Matrix<elemType> &m ); }; //====================================================================== template<class Type> istream &operator >> ( istream &is, Matrix<Type> &m ); template<class Type> class Matrix{ public: //.... friend Matrix<Type> &operator + <Type>( Matrix<Type> &m1, Matrix<Type> &m2 ); friend ostream &operator << <Type>( ostream &os, Matrix &m ); friend istream &operator >> <Type>( istream &is, Matrix &m ); }; template<class Type> Matrix<Type> & operator + ( Matrix<Type> &m1, Matrix<Type> &m2 ){ // 定义 } template<class Type> ostream & operator << ( ostream &os, Matrix<Type> &m ){ // 定义 } template<class Type> istream &operator >> ( istream &is, Matrix<Type> &m ){ // 定义 }