一个插入/提取运算符重载函数为什么需要 ostream/istream 参数?

4
考虑下面带有重载插入和提取运算符的代码。
#include <iostream>

using namespace std;

class CTest
{
    string d_name;
public:
    friend ostream & operator<<(ostream & out, CTest & test);
    friend istream & operator>>(istream & in, CTest & test);
};

ostream & operator<<(ostream & out, CTest & test)
{
    out << "Name: " << test.d_name;
    return out;
}

istream & operator>>(istream & in, CTest & test)
{
    cout << "Enter your name: ";
    string name;
    if(in >> name)
        test.d_name = name;

    return in;
}

int main()
{
    CTest test;
    cin >> test;   // (1)
    cout << test;  // (2)
}

针对这个问题,参数 ostream & out 和 istream & in 的意义是什么? 由于我们只能看到一个参数(cin >> test 或 cout << test),那么在调用程序中,ostream/istream 引用在哪里传递了 (1) 或 (2)?


4
cin >> test 中有两个参数。 - juanchopanza
1
istream 不是 cin 的同义词,而是它的类型。 - Passer By
如果您没有将流传递给您的operator,那么该函数如何知道应将数据写入哪个流或从哪个流中读取数据?_流操作符_旨在与任何流(std in和out、文件流、网络流、用户定义的流等)一起使用。因此,问题应该是这些运算符函数如何获得两个参数。 - t.niese
你的插入运算符(<<)应该使用const引用:CTest const& test - Galik
我的疑问是,对于一个函数,参数是放在括号里传递的,例如:fn(p1, p2); 但这里我无法理解这个函数的设计,因为参数是以非常规的方式传递的:cout(parameter 1) << test(parameter 2)。 - r18ul
了解“运算符重载”。 - Pete Becker
3个回答

4
由于在 cin >> testcout << test 中都存在两个参数。 cin 类型为 istreamcout 类型为 ostream
这些类型可能不仅限于 coutcin。例如,它们可能是 cerrclogstringstream
因此需要两个参数,一个是流变量,另一个是要流式输出的对象。

1
其他的istreamostream可以包括文件流、cerrclog(虽然很少使用它),以及stringstream。这是我能想到的标准库中的全部,但我可能会漏掉一些,而其他像Boost这样的库则实现了它们自己的流类。 - Daniel H
@gsamaras 我无法理解这个函数的设计,它以这种非传统的方式接受参数。 你能否请给我一些提示? - r18ul
@Rahul 例如,你所拥有的 << 运算符可以将 test.d_name 输出到 coutcerr 中。你希望具有这种灵活性,因为现在你可以编写 (cout << testcerr << test)。希望这能帮到你。 - gsamaras
谢谢回复。是的,我明白使用istream/ostream是为了方便而实现与cerr等相同的功能。我的疑问是 - 对于一个函数,参数是在括号中传递的,例如 - fn(p1,p2); 但是在这里,我无法理解这个函数的设计,其中参数是以非常规方式传递的。cout(参数1)<< test(参数2)。 - r18ul

0
cin >> test;

这里,左操作数是类型为std::istreamcin对象,右操作数是您的CTest类对象。

>>运算符的原型

friend istream& operator >> (istream& s, Your class &);

所以,内部我们传递了两个参数。


0
为了更好地理解这两个参数的来源,您可以将您的main()函数重写如下:
int main()
{
    CTest test;
    operator>>(std::cin, test);
    operator<<(std::cout, test);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接