However,how can a function be deprived of parentheses?
函数的名称,而不是(),只是对该函数的引用.它与任何其他类型完全相同:
void foo(int) {}
char x = 'a';
char *p = &x;
int main()
{
p; // Refers to p
*p; // Dereferences p (refers to whatever p points to)
foo; // Refers to foo
foo(42); // Calls foo
}
std :: endl是一个函数(实际上是一个函数模板),它接受一个类型为“a stream”的参数,并通过将EOL表示插入到该流中然后将其刷新来工作.你可以像其他任何函数一样使用它,如果你想:
std::endl(std::cout);
最后一个难题是标准库提供了运算符的重载(同样,模板)<
Stream& operator<< (Stream &s,const Function &f)
{
f(s);
return s;
}
因此,调用std :: cout<< std :: endl调用该操作符重载,后者又调用std :: endl(std :: cout),它执行EOL插入刷新. 至于哪种形式是首选的(直接调用vs.<< operator),它肯定是使用<<.>
std::cout << "Temperature: " << std::fixed << std::setprecision(3) << temperature << " (rounds to " << std::setprecision(1) << temperature << ')' << std::endl;