我正在创建一个 LinkedList 类。我很难将另一个节点添加到我的列表中。
这是我目前所拥有的:
template<typename T>
class LinkedList
{
private:
T element;
T *next;
public:
LinkedList();
LinkedList(T element);
void add(LinkedList<T> &otherList);
void print();
};
template<typename T>
LinkedList<T>::LinkedList()
{
next = NULL;
}
template<typename T>
LinkedList<T>::LinkedList(T element)
{
this->element = element;
next = NULL;
}
template<typename T>
void LinkedList<T>::add(LinkedList<T> &otherList)
{
next = &otherList;
}
template<typename T>
void LinkedList<T>::print()
{
LinkedList<T> *current = this;
while (current != NULL)
{
std::cout << current->element;
current = current->next;
}
}
int main()
{
LinkedList<std::string> myFirst("First");
LinkedList<std::string> mySecond("Second");
myFirst.add(mySecond);
myFirst.print();
return 0;
}
但是,如果我进行更改,这会起作用:
void add(const LinkedList<T> &otherList);
template<typename T>
void LinkedList<T>::add(const LinkedList<T> &otherList)
{
next = &otherList; //now an error right here
}
然后我得到一个错误说明:
Assigning to 'LinkedList<std::__1::basic_string<char> > *' from incompatible type 'const LinkedList<std::__1::basic_string<char> > *'
为什么会出现这个错误?
最佳答案
next
是 T*
,并且您正在尝试分配 const LinkedList<T>*
我想你的意思是像 next = &(otherList.element)
(尽管如此,我认为您的列表语义有些破损 — 元素通常不应被多个容器共享,除非您非常非常清楚所有权语义)。
与您的说法相反,your first program doesn't work either出于同样的原因。
关于C++通过引用传递然后设置指向对象的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20479253/