C++通过引用传递,然后设置指向该对象的指针

C++ pass by reference then set a pointer to the object

本文关键字:对象 指针 设置 然后 引用 C++      更新时间:2023-10-16

我正在创建一个类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)(尽管即使在那时,我也认为你的列表语义有点混乱&元素通常不应该由多个容器共享,除非你非常非常清楚所有权语义)。

与你的说法相反,出于同样的原因,你的第一个程序也不起作用。