我正在做链接列表的代码,当我尝试用g ++编译时,我得到这个奇怪的错误。
/cygdrive/c/Users/Blas/AppData/Local/Temp/ccEcixjp.o: In function `Node': /cygdrive/c/Users/Blas/Documents/blas.borde/trunk/Cs170/Lab6/List.h:50: undefined reference to 'CS170::ListLab::Node::nodes_alive' /cygdrive/c/Users/Blas/Documents/blas.borde/trunk/Cs170/Lab6/List.h:50: undefined reference to 'CS170::ListLab::Node::nodes_alive' /cygdrive/c/Users/Blas/Documents/blas.borde/trunk/Cs170/Lab6/List.h:56: undefined reference to 'CS170::ListLab::~Node::nodes_alive'
这是我的代码
namespace CS170 { namespace ListLab { struct Node { int number; // data portion Node *next; // pointer to next node in list static int nodes_alive; // number of nodes still around // Non-default constructor Node(int value) { number = value; next = 0; nodes_alive++; // a node was created } // Destructor ~Node() { nodes_alive--; // a node was destroyed } }; } }
奇怪的是,我已经定义了nodes_alive,所以我不知道为什么链接器说variables没有被定义。 也许有什么明显的,我失踪了。 请,我需要帮助。
看来你只是在类定义中声明了静态数据成员node_alive,而没有在类之外定义它。 在全局命名空间的某些模块中写入
int CS170::ListLab::Node::nodes_alive;
要么
namespace CS170 { namespace ListLab { int Node::nodes_alive; } }
虽然它将被隐式地初始化为零,但是您可以在其定义中明确指定0作为初始化器。