考虑下面带有重载插入和提取运算符的代码。
#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)?
cin >> test
中有两个参数。 - juanchopanzaistream
不是cin
的同义词,而是它的类型。 - Passer Byoperator
,那么该函数如何知道应将数据写入哪个流或从哪个流中读取数据?_流操作符_旨在与任何流(std in和out、文件流、网络流、用户定义的流等)一起使用。因此,问题应该是这些运算符函数如何获得两个参数。 - t.niese<<
)应该使用const引用:CTest const& test
。 - Galik