簡體   English   中英

缺少符號錯誤(未定義的引用)

[英]Missing symbol error (undefined reference)

我試圖用 DS.h 中的聲明和 DS.cpp 中的實現來定義 class DS 代碼非常小,所以這里是清單:

 /*
  * DS.h
  */

 #ifndef DS_H_
 #define DS_H_

 #include "Node.h"

 template<class T>
 class DS
 {
     public:
         static const int BST;
         static const int SLL;
         static const int DLL;

         DS(const int);
         ~DS();

     private:
         int m_type;
         Node<T> *head;
 };

 #endif /* DS_H_ */

和,

 /*
  * DS.cpp
  */

 #include "DS.h"

 template<class T> const int DS<T>::BST = 0;
 template<class T> const int DS<T>::SLL = 1;
 template<class T> const int DS<T>::DLL = 2;

 template<class T>
 DS<T>::DS(const int type) :
     m_type(type), head(0)
 {
 }

 template<class T>
 DS<T>::~DS()
 {
 }

主要程序是:

 #include "DS.h"

 int main()
 {
     DS<int> *sll1 = new DS<int> (DS<int>::SLL);
     delete sll1;
     return 0;
 }

當我嘗試編譯此程序時,我收到以下錯誤:

 g++ -O2 -g -Wall -Wextra -Weffc++ -fmessage-length=0   -c -o Node.o Node.cpp
 g++ -O2 -g -Wall -Wextra -Weffc++ -fmessage-length=0   -c -o DS.o DS.cpp
 g++ -O2 -g -Wall -Wextra -Weffc++ -fmessage-length=0   -c -o main.o main.cpp
 DS.h: In instantiation of ?DS<int>?:
 main.cpp:13:   instantiated from here
 DS.h:15: warning: ?class DS<int>? has pointer data members
 DS.h:15: warning:   but does not override ?DS<int>(const DS<int>&)?
 DS.h:15: warning:   or ?operator=(const DS<int>&)?
 g++ -o ds.exe Node.o DS.o main.o 
 main.o: In function `main':
 /cygdrive/c/Documents and Settings/ansrivastava/My Documents/src/ds/main.cpp:13: undefined reference to `DS<int>::SLL'
 /cygdrive/c/Documents and Settings/ansrivastava/My Documents/src/ds/main.cpp:13: undefined reference to `DS<int>::DS(int)'
 /cygdrive/c/Documents and Settings/ansrivastava/My Documents/src/ds/main.cpp:14: undefined reference to `DS<int>::~DS()'
 collect2: ld returned 1 exit status
 make: *** [ds.exe] Error 1

現在,如果我從 DS.cpp 中刪除所有代碼並將其粘貼到 DS.h 中,一切都可以正常編譯。 知道我在做什么錯嗎?

Now, if I remove all the code from DS.cpp and paste it into DS.h, everything compiles fine. Any idea what am I doing wrong?

請參閱 C++ 常見問題解答中有關單獨編譯的此條目

必須立即初始化static const量值成員,就像任何const量值一樣。 所以:

     static const int BST = 0;
     static const int SLL = 1;
     static const int DLL = 2; 

您自己說如果您將代碼從 DS.cpp 移動到 DS.h 並詢問您做錯了什么,它編譯得很好。 答案就是,你在 .cpp 文件中有代碼。 編譯 DS.cpp 時,它不會定義 DS < int > 因為這是在您的主文件中完成的,因此需要包含 DS.h

const int DS<int>::BST = 0;
const int DS<int>::SLL = 1;
const int DS<int>::DLL = 2;

將被編譯。 不要忘記 DS 只是一個模板。 編譯 DS.cpp 沒有任何意義,因為它只包含模板。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM