Vector中作为全局变量时注意的问题
案例:两个文件:
//Class.h====================================================
#ifndef CLASS_H
#define CLASS_H
#include <vector>
class Node;
class Node
{
public:
void Register()
{
Node::nodeCollection.push_back(this);
}
public:
static std::vector<Node*> nodeCollection;
};
#endif
//Class.h====================================================
#ifndef CLASS_H
#define CLASS_H
#include <vector>
class Node;
class Node
{
public:
void Register()
{
Node::nodeCollection.push_back(this);
}
public:
static std::vector<Node*> nodeCollection;
};
#endif
//main.cpp =====================================================
#include "Class.h"
#include <iostream>
using namespace std;
答案:即
此处添加
std::vector<Node*> Node::nodeCollection;
int main()
{
Node aNode;
Node* pNodeA = new Node();
pNodeA->Register();
Node* pNodeB = new Node();
pNodeB->Register();
for (int i = 0; i < Node::nodeCollection.size(); i++)
{
if (Node::nodeCollection[i] != NULL)
{
delete Node::nodeCollection[i];
Node::nodeCollection[i] = NULL;
}
}
cout << "done!" << endl;
cin.ignore();
return 1;
}
//======================================================================
编译时出错,会提示error LNK2001unresolved external symbol****
{
Node aNode;
Node* pNodeA = new Node();
pNodeA->Register();
Node* pNodeB = new Node();
pNodeB->Register();
for (int i = 0; i < Node::nodeCollection.size(); i++)
{
if (Node::nodeCollection[i] != NULL)
{
delete Node::nodeCollection[i];
Node::nodeCollection[i] = NULL;
}
}
cout << "done!" << endl;
cin.ignore();
return 1;
}
//======================================================================
编译时出错,会提示error LNK2001unresolved external symbol****
正确回答:
在
int main()
之前加一句
;
std::vector<Node*> Node::nodeCollection;
std::vector<Node*> Node::nodeCollection;