【问题标题】:User-defined Output Stream Manipulators in CC 语言中用户定义的输出流操纵器
【发布时间】:2013-07-05 01:25:39
【问题描述】:

我正在学习C++,在用户定义的输出流操作器部分,我卡住了。 这是示例代码:

    #include <iostream>
     using std::cout;
     using std::flush;
     using std::ostream;

    ostream& endLine( ostream& output )
    {
      return output << '\n' << flush;
    }

    int main()
    {
       cout << "Testing:" << endLine;
       return 0;
    }

我的问题是,在 endLine 的定义中,有一个参数。但是在main函数中,为什么它只有endLine,没有括号和相应的参数。

【问题讨论】:

  • 您实际上并没有问问题。如果您没有明确提出问题,我们必须猜测您想要解释的内容。

标签: c++


【解决方案1】:

std::basic_ostream 有多个 operator&lt;&lt; 重载,其中一个具有以下签名:

basic_ostream& operator<<( basic_ostream& st, 
                       std::basic_ostream& (*func)(std::basic_ostream&) );

也就是说,这个函数接受一个指向一个函数的指针,该函数接受并返回std::ios_base。该方法由该函数调用,并被合并到输入/输出操作中。从而使这成为可能:

std::cout << endLine;

那么会发生什么,endLine 被转换为一个函数指针,并且一个换行符将被写入流中,然后是一个刷新操作。

【讨论】:

    【解决方案2】:

    std::ostream 有一个operator&lt;&lt; 的重载,它接受一个指向函数的指针(或者可以调用的类似函数),该函数接受指针,并调用函数,将自身作为参数传递给函数:

    std::ostream &operator<<(std::ostream &os, ostream &(*f)(ostream &os)) { 
        return f(*this);
    }
    

    ostream 内置的版本来自std::ios_base(这是它用于参数和返回的类型),但如果您尝试编写自己的版本,通常希望使用std::ostream而是。

    【讨论】:

    • 哦,太好了。感谢您的详细解释。
    【解决方案3】:

    cout 的左移运算符以cout 作为参数调用endLine。写函数名时不需要调用函数(技术上的函数指针);您可以将它们作为值传递并让其他代码稍后调用它们。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-22
      • 1970-01-01
      • 2010-10-06
      • 1970-01-01
      • 2010-12-03
      • 1970-01-01
      相关资源
      最近更新 更多