gpt4 book ai didi

c++ - 为什么插入/提取运算符的重载函数需要 ostream/istream 参数?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:07:20 24 4
gpt4 key购买 nike

考虑以下带有重载插入和提取运算符的代码。

#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),在调用方中,在 (1) 或 (2) 处传递的 ostream/istream 引用在哪里?

最佳答案

因为在cin >> testcout << test , 存在两个参数。

cin类型为 istream .

cout类型为 ostream .

这些类型可能不是cout。和 cin .例如,它们可以是 cerr , clog , 或 stringstream .

这就是为什么您需要两个参数,因为一个是流的变量,另一个是要流式传输的对象。

关于c++ - 为什么插入/提取运算符的重载函数需要 ostream/istream 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46723073/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com