zLe*_*eon 3 c++ function ostream manipulators operator-keyword
我知道没有括号就不能调用函数,但是,假设我有这段源代码:
#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
Run Code Online (Sandbox Code Playgroud)
没有左移位运算符重载任何,但是当我打电话的test(ostream& os)功能中cout的main功能,它不需要任何括号.我的问题是为什么?
左移运算符没有任何超载
是的,它是定义的<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); }
Run Code Online (Sandbox Code Playgroud)
cout << test使用这些重载中的第一个,相当于cout.operator<<(&test),这样就return test(*this);可以在重载内部进行调用operator<<.
ostream对于这种情况,运算符<<的重载:
basic_ostream& operator<<(
std::basic_ostream<CharT,Traits>& (*func)(std::basic_ostream<CharT,Traits>&) );
Run Code Online (Sandbox Code Playgroud)
调用func(*this);. 这些重载用于实现输出I/O操纵器,例如std :: endl.