未定义的引用错误 [英] Undefined reference error

查看:117
本文介绍了未定义的引用错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

//XX.h
template <class T> class XX
{
public:
  XX();
  ~XX();
  static T* get() {//def}
  static void set(T* data){//def}
  static void init();
 private:
  static T *data;
};

//XX.C
template <class T> T* XX<T>::data = 0;
template <class T> 
void XX<T>::init()
{
  data = 0;
}

//Test.h
#include <XX.h>
class Sample{
public:
static void someFunc(int *x){XX<int>::set(x);}
};

//Test.C
int main()
{
int x = 100;
Sample::someFunc(&x);
return 0;
}







这是我的应用程序的示例代码,我未定义XX< int> :: data和XX< int> init()的引用错误。任何人都可以帮我解决这个错误。在此先感谢!!




This is sample piece of code from my app, i am getting undefined reference error for XX<int>::data and XX<int>init() both. Can anybody help me resolve this error. Thanks in advance!!

推荐答案

您无法将模板代码移动到C文件中 - 它必须位于头文件中!或者至少它必须可以从使用这个类的文件访问(所以理论上你可以包含.c文件和.h文件)



原因是只有在模板实例化时才会编译类,此时实例化它的文件必须能够访问完整的实现。
You can''t move template code into a C file - it must be in the header file! Or at least it must be accessible from the file that uses this class (so you could in theory include the .c file along with the .h file)

The reason is that the class will be compiled only when the template gets instantiated, and at that point the file that instantiates it must have access to the full implementation.


你的语法错误在这里


your syntax error is here

//XX.h
template <class t=""> class XX
{
public:
  XX();
  ~XX();
  static T* get() {//def} //here
  //solution
  static T* get() {}//def
  static void set(T* data){//def} //here
  static void init();
 private:
  static T *data;
};
 
</class>


显然你没有定义XX类< t>的构造函数和析构函数了。任何地方。



删除声明,然后导致生成默认构造函数/析构函数。或者在某处定义函数。
Obviously you have not defined the construtor and destructor of class XX<t> anywhere.

Either remove the declaration, which will then lead to the generation of default constructors/destructor. Or define the function somewhere.


这篇关于未定义的引用错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆