C++ c+中的运算符重载+;一个整数和一个对象

C++ c+中的运算符重载+;一个整数和一个对象,c++,operator-overloading,C++,Operator Overloading,我有一个关于运算符重载的作业。我做了11/13个,但我被困在最后2个(类似)。我有一个链表类,我被分配到重载list1+(inti),我已经这样做了。我还需要重载I+list1,这就是我遇到的困难,因为我还有一个cout作为非成员函数(它可能必须是朋友) 您可能还想将现有的文件重写为: SortedDoublyLinkedList operator+(const SortedDoublyLinkedList& list, int i) { ... } 您可能还想让一个调用另一

我有一个关于运算符重载的作业。我做了11/13个,但我被困在最后2个(类似)。我有一个链表类,我被分配到重载
list1+(inti)
,我已经这样做了。我还需要重载
I+list1
,这就是我遇到的困难,因为我还有一个
cout作为非成员函数(它可能必须是朋友)

您可能还想将现有的文件重写为:

 SortedDoublyLinkedList operator+(const SortedDoublyLinkedList& list, int i) 
   { ... }

您可能还想让一个调用另一个,或者,更好的是,让两个调用一个
SortedDoublyLinkedList::Add()
方法。

要实现
i+list1
,必须定义一个像

class SortedDoublyLinkedList {
...

friend SortedDoublyLinkedList operator+(int i, const SortedDoublyLinkedList &_list);
};

SortedDoublyLinkedList operator+(int i, const SortedDoublyLinkedList &_list) {
    SortedDoublyLinkedList newlist(_list);
    newlist.add(i);
    return newlist;
}

您提到的问题很可能是正交的。
可以考虑用左手边的参数调用成员运算符是否有意义……链接的副本清楚地描述了非成员运算符。它不必是
朋友
,有很多方法可以在不访问私有成员的情况下编写函数。没错,这个实现不需要是朋友。
 SortedDoublyLinkedList operator+(const SortedDoublyLinkedList& list, int i) 
   { ... }
class SortedDoublyLinkedList {
...

friend SortedDoublyLinkedList operator+(int i, const SortedDoublyLinkedList &_list);
};

SortedDoublyLinkedList operator+(int i, const SortedDoublyLinkedList &_list) {
    SortedDoublyLinkedList newlist(_list);
    newlist.add(i);
    return newlist;
}