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
标签:myOutText,100ask,c++,operator,book,操作符,重载,include,public 来源: https://www.cnblogs.com/coding8832/p/14462898.html