How to properly overload the << operator for an ostream?

前端 未结 5 1241
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 04:54

I am writing a small matrix library in C++ for matrix operations. However my compiler complains, where before it did not. This code was left on a shelf for 6 months and in b

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 05:24

    Assuming that we're talking about overloading operator << for all classes derived from std::ostream to handle the Matrix class (and not overloading << for Matrix class), it makes more sense to declare the overload function outside the Math namespace in the header.

    Use a friend function only if the functionality cannot be achieved via the public interfaces.

    Matrix.h

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

    Note that the operator overload is declared outside the namespace.

    Matrix.cpp

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

    On the other hand, if your overload function does need to be made a friend i.e. needs access to private and protected members.

    Math.h

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

    You need to enclose the function definition with a namespace block instead of just using namespace Math;.

    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;
        }                 
    }
    

提交回复
热议问题