0

我试图用 DS.h 中的声明和 DS.cpp 中的实现来定义一个类 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 中,一切都可以正常编译。知道我在做什么错吗?

4

3 回答 3

3

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++ FAQ 中有关单独编译的此条目。

于 2011-04-27T10:05:14.150 回答
0

您自己说如果您将代码从 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 没有任何意义,因为它只包含模板。

于 2011-04-27T10:21:02.900 回答
0

static const成员必须立即初始化就像任何const值一样。所以:

     static const int BST = 0;
     static const int SLL = 1;
     static const int DLL = 2; 
于 2011-04-27T09:58:45.483 回答