用户定义的C输出流操纵器

用户定义的C输出流操纵器

本文介绍了用户定义的C输出流操纵器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我正在学习C ++,在用户定义的输出流操纵器部分,我陷入了困境。
这是示例代码:

I am learning C++, and in the part of user-defined output stream manipulatior, I am stuck.This is the example code:

    #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的定义中有一个参数。但是在主函数中,为什么它是仅不带括号和相应参数的endLine。

My question is, in the definition of endLine, there is an argument. But in the main function, why it is endLine only without brackets and according arguments.

推荐答案

std: :basic_ostream 有几个 operator<< 的重载,其中一个具有以下签名:

std::basic_ostream has several overloads of operator<<, one of which has the following signature:

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


也就是说,此函数使用指向两个函数的指针并返回 std :: ios_base 。该方法由该函数调用,并包含在输入/输出操作中。从而使这成为可能:

That is, this function takes a pointer to a function that both takes and returns std::ios_base. The method is called by this function and is incorporated into the input/output operation. Thereby making this possible:

std::cout << endLine;

所以将发生的是 endLine 是转换为函数指针,然后将新行字符写入流,然后执行刷新操作。

So what will happen is that endLine is converted into a function pointer and a new line character will be written to the stream and afterwards a flush operation.

这篇关于用户定义的C输出流操纵器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 17:56