[英]Calling a function which manipulates the ostream doesn't require parentheses. C++
我知道没有括号就不能调用函数,但是,假设我有这段源代码:
#include<iostream>
using namespace std;
ostream& test(ostream& os){
os.setf(ios_base::floatfield);
return os;
}
int main(){
cout<<endl<<scientific<<111.123456789;
cout<<endl<<test<<111.123456789;
}
/// Output:
/// 1.11235e+002
/// 111.123
左移运算符没有任何重载,但是当我在main
函数的cout
中调用test(ostream& os)
函数时,它不需要任何括号。 我的问题是为什么?
左移运算符没有任何超载
是的,它是在<ostream>
定义的。
它使用完全相同的技术,允许endl
和scientific
工作。 有一个带有函数指针的重载,它在写入流时调用函数指针。
basic_ostream
具有接受函数指针的这些成员函数:
// 27.7.3.6 Formatted output:
basic_ostream<charT,traits>&
operator<<(basic_ostream<charT,traits>& (*pf)(basic_ostream<charT,traits>&))
{ return pf(*this); }
basic_ostream<charT,traits>&
operator<<(basic_ios<charT,traits>& (*pf)(basic_ios<charT,traits>&))
{ return pf(*this); }
basic_ostream<charT,traits>&
operator<<(ios_base& (*pf)(ios_base&))
{ return pf(*this); }
cout << test
使用第一个重载,相当于cout.operator<<(&test)
,它return test(*this);
所以调用发生在重载的operator<<
。
对于这种情况, ostream
有运算符<<的重载:
basic_ostream& operator<<(
std::basic_ostream<CharT,Traits>& (*func)(std::basic_ostream<CharT,Traits>&) );
调用func(* this);. 这些重载用于实现输出I / O操纵器,例如std :: endl。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.