我正在尝试为类
的静态成员找到链接器错误的解决方案以下是代码:
//node.h
class Node{
public:
static vector<Node*> nodePointers; //i will use these pointers to access multiple objects of the same class
int id;
int a;
int b;
friend int add(Node*,int);
void itsMyLife(int);
Node();
};
//node.cpp
void Node::itsMyLife(int x){
int answer=0;
if(nodePointers[x]->a<100){
answer=add(this,nodePointers[x]->id);
}
cout<<"Answer in node "<<id<<" is "<<answer<<endl;
}
int add(Node* x, int y){
return x->a+x->nodePointers[y]->b;
}
//main.cpp
int* myInts=new int[10];
vector<int*> intVectors;
for(int i=0;i<10;i++)
intVectors[i]=&myInts[i];
Node* myNodes=new Node[2];
for(int i=0;i<2;i++)
myNodes[0].nodePointers[i]=&myNodes[i];
myNodes[0].id=0;
myNodes[0].a=10;
当我编译并链接时,它给出了错误:
对Node :: nodePointers的未定义引用
为什么我收到此错误?我将非常感谢你的帮助。再次感谢。
答案 0 :(得分:0)
静态类成员应该在类定义中初始化(1)一次(2)。通常最好的地方是相关的.cpp文件。
换句话说,你应该向你的node.cpp添加这样的东西:
vector<Node*> Node::nodePointers;