3

我知道没有括号就不能调用函数,但是,假设我有这段源代码:

#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

左移运算符没有任何重载,但是当我test(ostream& os)coutat函数中调用该函数时main,它不需要任何括号。我的问题是为什么?

4

2 回答 2

6

左移运算符没有任何重载

是的,它定义在<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<<

于 2015-08-24T08:47:32.423 回答
6

ostream在这种情况下,运算符 <<重载:

basic_ostream& operator<<(
    std::basic_ostream<CharT,Traits>& (*func)(std::basic_ostream<CharT,Traits>&) );

调用 func(*this);。这些重载用于实现输出 I/O 操纵器,例如 std::endl。

于 2015-08-24T08:47:36.753 回答