【发布时间】:2017-10-13 05:27:51
【问题描述】:
考虑以下带有重载插入和提取运算符的代码。
#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
【问题讨论】:
-
cin >> test中有两个参数。 -
istream不是cin的同义词,而是它的类型。 -
如果你不将流传递给
operator,函数应该如何知道它应该将数据写入哪个流或从哪个流读取它? 流式操作符 设计用于处理任何流(标准输入和输出、文件流、网络流、用户定义的流……)。所以问题应该是这些运算符函数如何获得两个参数。 -
您的 插入操作符 (
<<) 应该使用 const ref:CTest const& test。 -
我的疑问是 - 对于函数,参数在括号中传递,例如 - fn(p1, p2);但是在这里我无法理解这个函数的设计,其中参数是非常规地传递的。 cout(参数 1)
标签: c++ oop operator-overloading