[英]Why use std::ostream and friend for << operator overloading?
我想重载运算符 << 以使用 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
}
而且我也不明白为什么我们必须将其设为好友功能? 如果我删除关键字朋友,它会给我一个错误,<<运算符是一个二元运算符。 我正在使用 Xcode。
列表.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);
};
在运算符 << 重载中,您不应该使用 cout,您应该使用您收到的 ostream 作为参数,只需更改os
的cout
。 这是因为 cout 将打印您正在返回的输出流。
您需要将该运算符重载为友元函数,因为即使该运算符不是类的一部分,它也可以访问类的私有属性和函数,因此它可以访问元素并打印它们。
运算符<<
是一个二元运算符,这意味着它需要左侧一个操作数和一个右侧操作数。 例如,当您编写cout << "Hello World"
,左侧操作数是ostream
类型的cout
,右侧操作数是字符串"Hello World"
。 同样,要为您的一个类重载运算符,您必须定义左侧操作数和右侧操作数,就像重载加号 (+) 运算符或任何其他二元运算符一样,需要您定义什么是操作数。 因此, os
应该用在你写cout
,如已经指出了以前的答案,这将有“价值” cout
如果左侧opernad是cout
。
至于返回os
,这样做的原因是为了能够链接多个打印语句。 可以使用整数来写cout << 3 << 5;
,因为最初评估第一个<<
运算符,打印 3,然后返回 os 并作为左侧操作数传递给下一个<<
。 如果重载的运算符不返回os
,这将无法用于您的类的对象。
最后,正如已经说过的,重载应该是类的朋友,因为它需要访问其私有成员,而且由于它不是类的成员函数,除非它是它的朋友,否则它不能拥有它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.