C++ 操作员<&书信电报;c+中的字符串流重载+; 问题:

C++ 操作员<&书信电报;c+中的字符串流重载+; 问题:,c++,C++,从重载的运算符 我的问题是,为什么我只得到流的第一位 正如在注释中提到的,在第一个Debug::operator之后的任何进一步调用如果您要使用该代码,那么它的行为就非常清楚了(提示:您的operator之一您很清楚您的第一个 #include <iostream> #include <sstream> #include <string> class Debug { private: std::stringstream stream; public:

从重载的
运算符
我的问题是,为什么我只得到流的第一位


正如在注释中提到的,在第一个
Debug::operator之后的任何进一步调用如果您要使用该代码,那么它的行为就非常清楚了(提示:您的
operator之一您很清楚您的第一个

#include <iostream>
#include <sstream>
#include <string>
class Debug {
private:
    std::stringstream stream;
public:
    std::string str() const{
        return stream.str();
    }
    std::stringstream& operator<<(std::string &s) {
        stream << s;
        std::cout << s;
        return stream;
    }
    std::stringstream& operator<<(const char s[]) {
        stream << s;
        std::cout << s;
        return stream;
    }
};
std::ostream &operator<<(std::ostream &output, const Debug &d) {
    output << d.str();
    return output;
}
int main() {
    Debug debug;
    std::string str("Bad input");
    debug << "Hello guys, " << "I can't get here!" << str << "\n";
    std::cout <<"\n\n"<< debug;
    std::cin.get();
    return 0;
}
class Debug {
    std::ostream& os_;
public:
    Debug(std::ostream& os) : os_(os) {}
    template<typename T>
    Debug& operator<<(T val) {
       // Intercept whatever you want to intercept here ...
       os_ << val;
       return *this;
    }
};
    debug << "Hello guys, " << "I can't get here!" << str << "\n";
int main() {
    Debug debug(std::cout);
    std::string str("Bad input");
    debug << "Hello guys, " << "I can't get here!" << str << "\n";
    return 0;
}
Hello guys, I can't get here!Bad input
#include <iostream>
#include <string>
#include <sstream>

class Debug {
    std::ostringstream os_;
public:
    template<typename T>
    Debug& operator<<(T val) {
       os_ << val;
       return *this;
    }

    // Overload the operator<< to output the buffered stuff
    friend std::ostream& operator<<(std::ostream& os, const Debug& debug) {
        os << debug.os_.str();
        return os;
    }
};


int main() {
    Debug debug;
    std::string str("Bad input");
    debug << "Hello guys, " << "I can't get here!" << str << "\n";
    std::cout << debug;
    return 0;
}