我试图在C++的链表中使用overload = operator并编写下面的代码.
template<class T>
class List {
public:
List();
List (T t_data);
List& operator=(const List<T> &L);
private:
template<class L>
class Node {
public:
L data;
Node *next;
Node *prev;
Node(T t_data) {
data = t_data;
next = prev = NULL;
}
};
Node<T> *head;
};
template<class T>
List& List<T>::operator=(const List<T> &L) {
Node<T> *t_head = head;
Node<T> *t_tail = head->prev;
Node<T> *temp;
while(t_head ! = t_tail) {
temp = t_head;
t_head = t_next;
delete temp;
}
head = L.head; …Run Code Online (Sandbox Code Playgroud) 我正在研究运算符重载=并看到下面的例子.
class Ratio {
public:
Ratio(int , int );
Ratio(const Ratio&);
Ratio& operator= (const Ratio&);
private:
int nNum, nDenum;
};
Ratio::Ratio(int n = 0, int d = 1) {
nNum = n;
nDenum = d;
}
Ratio::Ratio(const Ratio &T) {
nNum = T.nNum;
nDenum = T.nDenum;
}
Ratio& Ratio::operator= (const Ratio& R) {
nNum = R.nNum;
nDenum = R.nDenum;
return *this;
}
int main() {
Ratio r1;
Ratio r2(2,3);
r1 = r2;//STATEMENT 1
}
Run Code Online (Sandbox Code Playgroud)
这段代码运行良好,但我想知道为什么?由于函数operator=返回对Ratio对象的引用,但在STATEMENT 1中,我们没有在任何Ratio对象中获取返回引用.