gpt4 book ai didi

c++ - 调用操作 ostream 的函数不需要括号。 C++

转载 作者:太空狗 更新时间:2023-10-29 19:45:38 26 4
gpt4 key购买 nike

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

#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) 函数时 函数,它不需要任何括号。我的问题是为什么?

最佳答案

There isn't any overloading for the left-shift operator

是的,它在 <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<< 中.

关于c++ - 调用操作 ostream 的函数不需要括号。 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32177972/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com