如下代码怎样才能连续使用 << 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