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

标签 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> > *'

为什么会出现这个错误?

最佳答案

nextT* ,并且您正在尝试分配 const LinkedList<T>*

我想你的意思是像 next = &(otherList.element) (尽管如此,我认为您的列表语义有些破损 — 元素通常不应被多个容器共享,除非您非常非常清楚所有权语义)。

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

关于C++通过引用传递然后设置指向对象的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20479253/

相关文章:

c++ - 构建后缺少 *.lib 文件

c# - 什么是交换 2 个整数变量的 C 代码

c - 这段代码有什么有趣的错误吗?

c - 理解C中的解引用运算符和指针,以及一个小程序的逻辑

java - 我需要一些关于排序节点的解释

c - 实现带有喜欢列表的队列

c++ - 鼠标悬停时 GLSL 高亮网格

c++ - 限制数组类型的大小,同时还没有实例

c - 如果我尝试在 C 中定义一个指向字符串文字的指针,会发生什么情况?

c - 可以在单个 malloc 中分配 2D 数组并且仍然可以使用 [ ][ ] 语法吗?