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

static const値のメンバーは、他の値と同様に、すぐに初期化する必要がありconstます。それで:

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

You are saying yourself that it compiles fine if you move the code from DS.cpp to DS.h and asking what you are doing wrong. The answer is just that, you have the code in the .cpp file. When DS.cpp is compiled it will not define DS < int > since this is done in your main file, therefore DS.h needs to be included so

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

will be compiled. Dont forget that DS is just a template. It means nothing to compile DS.cpp since it only contains the template.

于 2011-04-27T10:21:02.900 に答える