如何在C++中正确使"<<"运算符过载?

How to properly overload the "<<" operator in C++?

本文关键字:lt 运算符 C++      更新时间:2023-10-16

我想做出类似std::cout的行为:

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

我试图实现一些我刚刚读到的东西,但它对我不起作用。我想在一个类中实现operator,我称之为MyBaseClass。我试过这个:

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

当我编译这个时,我得到:"调用‘MyBaseClass’的隐式删除默认构造函数"-我需要做什么来修复它?

OS X,Xcode,clang编译器,都是最新的。

您正试图将各种值类型输出到MyBaseClass对象中,因此需要支持相同的集合。我还将someOut更改为std::ostringstream,它能够累积输出。您可能同样希望它是传递给构造函数的调用者提供的流的std::ostream&。。。。

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