【发布时间】:2017-10-17 15:15:00
【问题描述】:
我想重载运算符
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
}
而且我也不明白为什么我们必须将其设为朋友功能?如果我删除关键字朋友,它会给我一个错误,即
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);
};
【问题讨论】:
-
这里的讨论中涵盖了方法和原因:stackoverflow.com/q/2828280/1531971
-
从 cout << 42 << mylist << "yo"
-
只是为了澄清一下:您可以在您的
class List中定义void operator>>(ostream& os);,并将其称为list >> cout;。不推荐,只是为了说明。
标签: c++