hov*_*ovo 26 c++ operator-overloading
我有以下代码:
#include <iostream>
using namespace std;
ostream& f(ostream& os) {
return os << "hi";
}
int main() {
cout << "hello " << f << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
不知何故,这是有效的 - 输出是"你好".这是如何被编译器解释的?我不明白如何将函数插入到流中.
Mat*_*lia 30
std::ostream
有一个operator<<
重载,它接收一个带有签名的函数的指针,例如你写的那个(这个列表中的数字11):
basic_ostream& operator<<(
std::basic_ostream<CharT,Traits>& (*func)(std::basic_ostream<CharT,Traits>&) );
Run Code Online (Sandbox Code Playgroud)
它只调用给定的函数传递自己作为参数.这个重载(以及几个类似的其他)允许你实现流操纵器,即你在流中输出的东西,<<
并从那里改变流的状态.例如,我们的(错误的)无处不在的版本std::endl
可以实现为
std::ostream &myendl(std::ostream &s) {
s<<'\n';
s.flush();
return s;
}
Run Code Online (Sandbox Code Playgroud)
然后可以完全用作"常规" std::endl
:
std::cout<<"Hello, World!"<<myendl;
Run Code Online (Sandbox Code Playgroud)
(实际的实现是模板化的,有点复杂,因为它甚至可以在宽流中工作,但你明白了)
std::ostream::operator<<
有一个重载接受函数作为参数; 并且该重载的主体是调用给定的函数.
这究竟是如何endl
工作的.endl
实际上是一个类似于的函数:
ostream &endl(ostream &os)
{
os << '\n';
os.flush();
return os;
}
Run Code Online (Sandbox Code Playgroud)