C++ 模板重載 << 運算符出錯 error: template-id ‘operator<< ’ for ‘std::ostream& operator<<(std::ostream&,

#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<< ’ for ‘std::ostream& operator<<(std::ostream&, Complex &)’ does not match any template declaration ios

苦苦詢問度娘,沒有找到和我一樣錯誤的,通過多方參考,其實只要在前面對友元函數和類進行申明便可函數

#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;
}
相關文章
相關標籤/搜索