为什么使用 std::ostream 和 friend 来<<运算符重载?
Why use std::ostream and friend for << operator overloading?
我想重载运算符<lt;使用std::cout打印列表,例如:
std::cout << list
//ouputs as {1,2,3,..}
经过搜索,我知道这可以使用ostream完成,但我不确定这是如何完成的。比如为什么有必要将ostream作为参考,然后返回?
操作员过载功能:
ostream& operator<<(ostream& os, List list)
{
Node* temp = list.start; //points to the start of the list
cout<<"{";
while(temp)
{
cout << temp->data; //cout all the data
if (temp->next != NULL)
cout << ",";
temp = temp->next;
}
cout<<"}" << endl;
return os; //returns the ostream
}
我也不明白为什么我们必须把它作为一个朋友函数?如果我删除关键字friend,它会给我一个错误<lt;运算符是一个二进制运算符。我正在使用Xcode。
List.hpp
class List
{
Node* start;
public:
List();
~List();
void emptyList();
void append(int);
void insert(int, int);
void print();
int length();
void remove_at(int);
int get_value_index(int);
int get_value_at(int);
List operator-(int);
friend ostream& operator<<(ostream& os,List); //why friend function??
List operator=(List);
List operator+(int);
List operator+(List);
int& operator[](const int ind);
bool operator==(List);
};
在运算符中<lt;重载不应该使用cout,应该使用正在接收的ostream作为参数,只需将cout
更改为os
即可。这是因为cout将打印您返回的输出流。
您需要使该运算符重载友元函数,因为即使该运算符不是类的一部分,它也可以访问类的私有属性和函数,因此可以访问元素并打印它们。
运算符<<
是一个二进制运算符,这意味着它需要一个操作数在左侧,一个在右侧。例如,写入cout << "Hello World"
时,左侧操作数是类型为ostream
的cout
,右侧操作数是字符串"Hello World"
。类似地,要重载某个类的运算符,必须定义左侧操作数和右侧操作数,就像重载加号(+)运算符或任何其他二进制运算符一样,需要定义操作数。因此,os
应该用于编写cout
的地方,正如前面的答案中已经指出的那样,如果左侧操纵词是cout
,它将具有"值"cout
。
至于返回os
,这样做的原因是为了能够链接多个打印语句。可以使用整数写入cout << 3 << 5;
,因为最初计算第一个<<
运算符,打印3,然后返回os,并将其作为左侧操作数传递给下一个<<
。如果重载运算符不返回os
,那么这将不可能对类的对象执行。
最后,正如已经说过的,重载应该是类的朋友,因为它需要访问其私有成员,并且由于它不是类的成员函数,所以它不能拥有它,除非它是它的朋友。
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 如何显式调用运算符<<
- 为什么COUT在朋友函数中不起作用,该功能超载了操作员&lt;&lt;这是一个iStream运算符
- C++运算符<<调用::ostream而不是std::osttream
- BOOST ::变体无法解决运算符&lt;&lt;对于STD :: Ostream
- 过载输出<<用于类的运算符,以打印其中的元组
- C++ostream:没有运算符匹配<<&应在'&'代币
- 重载运算符<<:此运算符函数的参数太多
- C++继承运算符<<
- 重载运算符<<用于模板类.即使使用好友关键字也无法获得私人会员
- 如何过载<<用于YAML::Emitter的运算符,以序列化包含另一个自定义类的向量的自定义类
- 为什么字符串流运算符<<擦除原始值
- 关于使用运算符<<为新手提供C++中的模板
- 我已经完成了<<运算符重载,但它'It’不起作用
- 重载运算符<<输出地址而不是数据成员
- 错误:没有匹配'运算符<<"在'std::cout
- 重载运算符<<用于ostream语法
- 当运算符<存在时,为什么要定义 LT?
- log4cxx访问异常,使用<<运算符和宏
- 重载<<运算符错误C2804:二进制'运算符<<'参数太多