3
#include <iostream>
#include <iomanip>
using namespace std;

ostream & currency(ostream & output)
{
    output << "RS ";
    return output;
}

int main()
{
    cout << currency  << 7864.5;
    return 0;
}

输出 :

 RS 7864.5

我不明白这似乎是如何工作的,即只使用函数的名称currency 来调用函数。这不应该是这样currency(cout),但使用它会产生输出。

 RS 1054DBCC7864.5
4

3 回答 3

9

该函数currency()是一个操纵器:流类具有特殊的重载输出运算符,将具有特定签名的函数作为参数。它们看起来像这样(省略了模板化):

class std::ostream
    public std::ios {
public:
     // ...
     std::ostream& operator<< (std::ios_base& (*manip)(std::ios_base&));            
     std::ostream& operator<< (std::ios& (*manip)(std::ios&));         
     std::ostream& operator<< (std::ostream& (*manip)(std::ostream&));
};

也就是说,currency作为函数指针传递,该指针以流作为其参数进行调用。

于 2012-11-18T16:14:41.013 回答
2

这有效(问题中的代码):

std::cout << currency << 7864.5;

这样做也是如此:

currency(std::cout) << 7864.5;

您显然尝试并抱怨但没有表现出来的是:

std::cout << currency(std::cout) << 7864.5;

这与以下内容相同:

ostream& retval = currency(std::cout); // prints "RS " as you expect
std::cout << retval; // oops, this is cout << cout, which is meaningless
std::cout << 7864.5; // prints "7864.5"
于 2012-11-18T16:15:38.123 回答
0

您的函数被视为 ostream 操纵器。

于 2012-11-18T16:12:20.553 回答