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

时间:2013-12-09 19:42:56

标签: c++ pointers linked-list pass-by-reference

我正在创建一个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> > *'

为什么我收到此错误?

1 个答案:

答案 0 :(得分:4)

nextT*,您正在尝试为其分配const LinkedList<T>*

我认为你的意思是next = &(otherList.element)(虽然我认为你的列表语义有点破坏 - 元素通常不应该由多个容器共享除非你非常,非常清楚所有权语义)。

与您的说法相反,your first program doesn't work either出于同样的原因。