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

Why does adding static data member result in linker failure?

本文关键字:链接 失败 添加 静态 数据成员 为什么      更新时间:2023-10-16

试图建立一个双向链表并将其打印出来。但是,添加"静态节点*上次添加"后,我收到链接器命令失败。不知道是什么原因。

另外,对于头节点,我想保持"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 中,您可以使用内联来定义静态变量

#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