简体   繁体   中英

How to properly overload the “<<” operator in C++?

I want to make a behavior like std::cout has:

int a = 10, b = 15, c = 7;
MyBaseClass << "a = " << a << ", b = " << b << std::endl;

I try to implement some things which I've just read but it doesn't work for me. I want to implement operator in one class which I call MyBaseClass . I tried this:

class MyBaseClass {
    private:
        std::ostream someOut;
    public:
        // My first try:
        std::ostream &operator<< ( std::ostream &out, const std::string &message ) {
        }

        // The second try:
        std::ostream &operator<< ( const std::string &message ) {
            someOut << message << std::endl;
            return someOut;
        }

        void writeMyOut() { 
            std::cout << someOut.str() 
        };
};

When I compile this I get: "Call to implicity-deleted default constructor of 'MyBaseClass'" - what do I need to do to fix it?

OS X, Xcode, clang compiler, all is up-to-date.

You're trying to output a variety of value types into the MyBaseClass object, so need to support the same set. I've also changed someOut to be a std::ostringstream , which is capable of accumulating the output. You might equally have wanted it to be a std::ostream& to a caller-provided stream passed to the constructor....

class MyBaseClass {
    private:
        std::ostringstream someOut;
    public:
        ...other functions...
        // The second try:
        template <typename T>
        MyBaseClass& operator<< ( const T& x ) {
            someOut << x;
            return *this;
        }

        void writeMyOut() const { 
            std::cout << someOut.str() 
        };
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM