- #include <iostream>
- namespace Test
- {
- class ostream
- {
- public:
- ostream &operator<<(int num)
- {
- printf("%d", num);
- return *this;
- }
- ostream &operator<<(char ch)
- {
- putchar(ch);
- return *this;
- }
- ostream &operator<<(ostream &(*pf)(ostream &out))
- {
- return pf(*this);
- }
- };
- ostream cout;
- ostream &endl(ostream &out)
- {
- putchar('\n');
- fflush(stdout);
- return out;
- }
- };
- int main()
- {
- int ch1 = 'a';
- char ch2 = 'a';
- Test::cout << ch1 << Test::endl;
- Test::cout << ch2 << Test::endl;
- return 0;
- }
复制代码
Test::cout << ch1 << Test::endl; // 调用的是 ostream &operator<<(int num)
Test::cout << ch2 << Test::endl; // 调用的是 ostream &operator<<(char ch)