为什么添加静态数据成员会导致链接器失败
Why does adding static data member result in linker failure?
试图建立一个双向链表并将其打印出来。但是,添加"静态节点*上次添加"后,我收到链接器命令失败。不知道是什么原因。
另外,对于头节点,我想保持"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
相关文章:
- mapreduce c编程与-fPIC链接失败,如何解决?
- 引用构造函数时链接失败
- 嵌入 python3.6 和 MinGW 在C++链接失败
- MAKE/CMAKE子目录链接到外部库的链接失败
- 与 CMAKE 的静态链接失败
- Android中的OpenCV 4.0.1链接失败
- 在静态库中链接失败,但链接共享库成功
- .so中存在的符号已编译.o引用了它,但链接失败
- 使用签证编译 dll / exe - 链接失败
- 在C++程序上使用mpicc链接失败
- 与iOS项目上的C 库链接失败
- C++链接失败-ld:找不到[makefile][gcc/cygwin]
- clang++链接失败:错误:源文件不是有效的UTF-8
- OpenCV:提供给imread()的链接失败
- 错误: /usr/bin/ld: 最终链接失败: 文件被截断
- 链接失败。如何使用'NtQuerySystemTime'窗口功能?
- 变量模板链接失败
- 克隆链接失败
- 安特尔和链接失败
- 最终链接失败:包含 windows.h 时参数无效