我正在学习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。
答案 0 :(得分:2)
std :: ostream有一个operator<<
的重载,它接受指向一个接受指针的函数(或类似的,可以被调用的东西)的指针,并调用该函数,将自身作为参数传递给功能:
std::ostream &operator<<(std::ostream &os, ostream &(*f)(ostream &os)) {
return f(*this);
}
内置于ostream
的版本来自std::ios_base
(这是它用于参数并返回的类型),但如果您正在尝试编写自己的类型,则通常需要请改用std::ostream
。
答案 1 :(得分:1)
std::basic_ostream
有几个operator<<
重载,其中一个具有以下签名:
basic_ostream& operator<<( basic_ostream& st, std::basic_ostream& (*func)(std::basic_ostream&) );
也就是说,这个函数接受一个指向函数的指针,该函数都接受并返回std::ios_base
。该方法由该函数调用,并包含在输入/输出操作中。从而使这成为可能:
std::cout << endLine;
所以会发生的是endLine
被转换为函数指针,并且新的行字符将被写入流中,然后是刷新操作。
答案 2 :(得分:0)
cout
的左移操作符以endLine
为参数调用cout
。在编写名称时不需要调用函数(技术上的函数指针);你可以将它们作为值传递,然后让其他代码调用它们。