我试图重载“+”运算符和“=”运算符,如下所示:
template<class T>
class LinkedList {
public:
LinkedList();
LinkedList(const LinkedList<T> &list); //Copy Constructor! Allocating new memory!
~LinkedList();
void PushNode(T new_data);
void Delete(LinkedNode<T> *pnode);
bool CopyDelete(LinkedNode<T> *pnode);
bool CopyDeleteMiddle();
void Show();
int get_length();
void Clear();
LinkedList<T> operator+(LinkedList<T> &list); //Overloading '+' operator
LinkedList<T> &operator=(LinkedList<T> &list); //Overloading '=' operator
LinkedNode<T> *head;
LinkedNode<T> *tail;
private:
int length;
};
template <class T>
LinkedList<T>& LinkedList<T>::operator=(LinkedList<T> &list)
{
if (&list != this) {
Clear();
LinkedNode<T> *pnode = list.head;
while(pnode)
{
PushNode(pnode->data);
pnode = pnode->next;
}
}
return *this;
}
template <class T>
LinkedList<T> LinkedList<T>::operator+(LinkedList<T> &list)
{
int carry = 0;
LinkedList<T> sum_list;
LinkedNode<T> *pnode = list.head;
LinkedNode<T> *pnode_this = head;
if (!pnode || !pnode_this)
throw("Invalid list!");
T digit, digit_this, digit_sum;
while(pnode || pnode_this)
{
if (!pnode) {
digit = 0;
digit_this = pnode_this->data;
pnode_this = pnode_this->next;
} else if (!pnode_this) {
digit = pnode->data;
digit_this = 0;
pnode = pnode->next;
} else {
digit = pnode->data;
digit_this = pnode_this->data;
pnode = pnode->next;
pnode_this = pnode_this->next;
}
digit_sum = digit + digit_this + carry;
if (digit_sum >=10) {
digit_sum-=10;
carry = 1;
} else {
carry = 0;
}
sum_list.PushNode(digit_sum);
}
return sum_list;
}
在我的主要功能中,我创建了三个这样的对象:
LinkedList<int> list1;
LinkedList<int> list2;
LinkedList<int> sum;
然后我添加了两个列表并将结果存储在 sum 中:
sum = list1+list2; //error occurred here!
我关于 LinkedList 类的所有声明和定义都在 MySinglyLinkedList.h 中,我的主要功能在 2_4.cc 中。
我在Linux(Ubuntu)中使用GCC 4.5.2编译2_4.cc,遇到如下错误:
2_4.cc:在函数“<code>int main(int, char**)”中:
2_4.cc:39:15: 错误: '<code>sum = LinkedList<T>::operator+(LinkedList<T>&) [with T = int](((链表<int>&)(& list2)))'</p>
MySinglyLinkedList.h:171:16:注意:候选人是:
LinkedList<T>& LinkedList<T>::operator=(LinkedList<T>&) [with T = int]
我的重载函数有什么问题吗?