链接以下代码失败:
#include <iostream>
#include <vector>
using namespace std;
class Node {
static vector<Node*> nodeList;
int id;
int value;
public:
Node(int);
};
Node::Node(int val) {
id = nodeList.size();
value = val;
nodeList.push_back(this);
}
我收到如下错误信息。
Undefined symbols for architecture x86_64: "Node::nodeList", referenced from: Node::Node(int) in test-028e68.o "_main", referenced from: implicit entry/start for main executable ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation)
问题出现在静态 vector 上。构造函数似乎找不到符号 nodeList。我不知道如何初始化它以使代码工作。
最佳答案
你必须明白声明和定义的区别:
static vector<Node*> nodeList; // declare static member
vector<Node*> Node::nodeList; // define static member
类似于下面的内容:
class Node {...
Node(int); // here is you declare
};
Node::Node() {} // here is you define
关于c++ - 找不到 C++ 类中的静态 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36991364/