# 如何正确地重载ostream的<<运算符？

``namespace Math { class Matrix { public: [...] friend std::ostream& operator<< (std::ostream& stream, const Matrix& matrix); } }` `

` `using namespace Math; std::ostream& Matrix::operator <<(std::ostream& stream, const Matrix& matrix) { [...] }` `

matrix.cpp：459：error：'std :: ostream＆Math :: Matrix :: operator <<（std :: ostream＆，const Math :: Matrix＆）'必须只有一个参数

` `namespace Math { class Matrix { public: [...] friend std::ostream& operator<< (std::ostream& stream, const Matrix& matrix) { [...] } }; }` `

` `namespace Math { class Matrix { public: [...] } std::ostream& operator<< (std::ostream& stream, const Math::Matrix& matrix); }` `

` `std::ostream& operator<<(std::ostream& stream, const Math::Matrix& matrix) { matrix.print(stream); //assuming you define print for matrix return stream; }` `

Matrix.h

` `namespace Math { class Matrix { //... }; } std::ostream& operator<<(std::ostream&, const Math::Matrix&);` `

Matrix.cpp

` `using namespace Math; using namespace std; ostream& operator<< (ostream& os, const Matrix& obj) { os << obj.getXYZ() << obj.getABC() << '\n'; return os; }` `

MATH.H

` `namespace Math { class Matrix { public: friend std::ostream& operator<<(std::ostream&, const Matrix&); }; }` `

Matrix.cpp

` `using namespace Math; using namespace std; namespace Math { ostream& operator<<(ostream& os, const Matrix& obj) { os << obj.XYZ << obj.ABC << '\n'; return os; } }` `

` `template<class T> auto operator<<(std::ostream& os, const T& t) -> decltype(t.print(os), os) { t.print(os); return os; }` `