2014-02-17 17 views
2

我正在爲鏈接列表編寫代碼,並且當我嘗試使用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,所以我不知道爲什麼鏈接器表示,變量沒有定義。也許有些事情顯而易見,我錯過了。 請,我需要幫助。

+1

你在哪裏定義'nodes_alive'?它是一個靜態成員變量,所以你*在結構中聲明它,但是你必須在外部定義*它。 – Beta

回答

3

看來你只是在類定義中聲明瞭靜態數據成員node_alive,而沒有在類之外定義它。在全局命名空間中的一些模塊寫

int CS170::ListLab::Node::nodes_alive; 

namespace CS170 
{ 
    namespace ListLab 
    { 
     int Node::nodes_alive; 
    } 
} 

雖然這將是零被隱式初始化可以明確指定0作爲在其定義的初始化。

+0

現在,它的工作。我忘了定義它,非常感謝。 – blastxu

相關問題