gpt4 book ai didi

c++ - 缺少符号错误( undefined reference )

转载 作者:行者123 更新时间:2023-11-28 01:06:29 27 4
gpt4 key购买 nike

我试图用 DS.h 中的声明和 DS.cpp 中的实现来定义类 DS代码非常小,所以这里是 list :

 /*
* 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 中,一切都可以正常编译。知道我做错了什么吗?

最佳答案

现在,如果我从 DS.cpp 中删除所有代码并将其粘贴到 DS.h 中,一切都可以正常编译。知道我做错了什么吗?

参见 this entry在关于单独编译的 C++ 常见问题解答中。

关于c++ - 缺少符号错误( undefined reference ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5802250/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com