c++ - 为什么添加静态数据成员会导致链接器失败?

标签 c++ linked-list static

<分区>

试图建立一个双向链表并打印出来。但是,我在添加“static Node* lastAdded”后收到链接器命令失败。不知道是什么原因。

此外,对于头节点,我希望“int data”保持未初始化状态。有没有比我下面的更好的方法来保持数据未初始化?

#include <iostream>
#include <string>

using namespace std;

struct Node {
    static Node* lastAdded;

    Node(const int data);   // General data node constructor
    Node(); // head constructor
    static void push(Node* previousNode);

    int data;
    Node* previous;
    Node* next;

};

Node::Node(const int data) {
    this->data = data;
}

Node::Node() {
    // Note that data is left uninitalized for head node
    previous = nullptr;
    next = nullptr;
    lastAdded = this;
}

static void push(Node* currentNode, Node* previousNode) {
    previousNode->next = currentNode;
    currentNode->previous = previousNode;
    currentNode->next = nullptr;
    Node::lastAdded = currentNode;
}

int main()
{
    Node* head = new Node();
    push(new Node(1), Node::lastAdded);
    push(new Node(12), Node::lastAdded);

    for (Node* temp = head; temp->next != nullptr; temp++) {
        if (temp->previous == nullptr)
            temp++;
        cout << temp->data << endl;
    }
}

最佳答案

您需要定义/初始化在类中声明的静态变量

static inline Node* lastAdded {nullptr};

在c++17中你可以使用inline来定义静态变量

#include <iostream>
#include <string>

using namespace std;

struct Node {
    static inline Node* lastAdded {nullptr};

    Node(const int data);   // General data node constructor
    Node(); // head constructor
    static void push(Node* previousNode);

    int data;
    Node* previous;
    Node* next;
};

Node::Node(const int data) {
    this->data = data;
}

Node::Node() {
    // Note that data is left uninitalized for head node
    previous = nullptr;
    next = nullptr;
    lastAdded = this;
}

static void push(Node* currentNode, Node* previousNode) {
    previousNode->next = currentNode;
    currentNode->previous = previousNode;
    currentNode->next = nullptr;
    Node::lastAdded = currentNode;
}

int main()
{
    Node* head = new Node();
    push(new Node(1), Node::lastAdded);
    push(new Node(12), Node::lastAdded);

    for (Node* temp = head->next; temp != nullptr; temp=temp->next) {
        cout << temp->data << endl;
    }
}

输出

1
12
Program ended with exit code: 0

关于c++ - 为什么添加静态数据成员会导致链接器失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54383749/

相关文章:

java - 静态导入的工作原理

java - 为泛型类的每个类型参数创建单独的单例的最佳习惯用法?

c++ - 在数组中插入数据时出错 - 数组下标的无效类型 'int[int]'

c++ - C的目标 "auto"关键字

java - java中自定义链接列表的自定义值类

scala - 如果单例如此糟糕,为什么 Scala 为它们提供语言支持?

c++ - 使用 Ford Fulkerson 算法找到边缘?

c++ - 为什么不能等待 Qt 进程在静态析构函数中完成?

c - 在邻接表中有自己的节点

algorithm - 最佳地重新排序钱包中的卡?