+-
c++ 怎样重载<<操作符才能连续使用?

请教,如下代码怎样才能连续使用 << 1 << 2 ?
还有 << CR ;

#include <iostream>

class myOutText{
public:
    int &operator << (auto s){
        std::cout << s;
    }

    void CR(){
        putchar('\n');
    }

};

int main(void)
{
    myOutText cout; 
    cout << "string<<";
    cout.CR();            // 怎样实现 cout << CR ; 
    cout << "1<<2<<\n";
    cout << 1 << 2;        // 怎样才能连续输出 12 
        
    return 0;
}
#include <iostream>

class myOutText{
public:
    myOutText &operator << (auto s) {   // 返回自身引用以支持连续操作
        std::cout << s;
        return *this;
    }

    void CR() {
        putchar('\n');
    }
};

int main(void)
{
    myOutText cout; 

    cout << "string<<";
    cout.CR(); 
    cout << "1<<2<<\n";
    cout << 1 << 2 << '\n';
        
    return 0;
}

输出:

book@100ask:~/Desktop$ g++ test.cpp 
book@100ask:~/Desktop$ ./a.out 
string<<
1<<2<<
12

谢谢指点,还有第二个问题也麻烦解决一下

怎样实现 cout << CR ; //相当于 std::cout << std::endl;

把回车输出给 myOutText cout ?

自己想了一个变通的办法:

#include <iostream>
#include <string>
#define CR "\n"

class myOutText{
public:
    myOutText &operator << (std::string s) {
        if (s==CR) std::cout << CR;
        else std::cout << "[string:" << s << "]";
        return *this;
    }

    myOutText &operator << (long double s) {
        std::cout << "[number:" << s << "]";
        return *this;
    }

};

int main(void)
{
    myOutText cout; 

    cout << "string1-" << "abc";
    cout << CR;
    cout << "1<<2<<:" << CR;
    cout << 1 << 23 << 1.2e-5 << 2.5 << CR << "xyz" << CR;
    cout << "end" << CR;
        
    return 0;
}

输出结果:

[string:string1-][string:abc]
[string:1<<2<<:]
[number:1][number:23][number:1.2e-005][number:2.5]
[string:xyz]
[string:end]

--------------------------------
Process exited after 0.01708 seconds with return value 0
请按任意键继续. . .

【新问题】
改进代码后,不用return *this; 也能连续使用,这又是为什么呢?

#include <iostream>
#include <string>
#include <typeinfo>
#define endl "\n"

class myOutText{
public:
    myOutText &operator << (auto s) {
        std::string str;
        if (typeid(s).name()==typeid(std::string("")).name()) str=s;
        if (str==endl) { 
            std::cout << endl;
            std::cout.flush();
        }
        else
            std::cout << s ;

        //return *this; //返回自身引用以支持连续操作
    }
};

int main(void)
{
    myOutText cout; 

    auto a = "abc";
    double b = 8.9;
    cout << "string1-" << a;
    cout << endl;
    cout << "1<<23<<4.56:" << endl;
    cout << 1 << 23 << 4.56e-7 << " "
         << b << endl << "crlf" << endl;
         
    std::string str = "endl";
    cout << str << endl << endl;
            
    return 0;
}

输出结果:

/*
string1-abc
1<<23<<4.56:
1234.56e-007 8.9
crlf
endl


--------------------------------
Process exited after 1.198 seconds with return value 0
请按任意键继续. . .
*/