C ++(gcc):未定义的引用`Stack< int> :: Stack(int)' [英] C++ (gcc): undefined reference to `Stack<int>::Stack(int)'

查看:1450
本文介绍了C ++(gcc):未定义的引用`Stack< int> :: Stack(int)'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:


我已经努力了一段时间,我在这里看看几个问题,但是对C ++新的我不能理解我错在哪里。



这是代码,我从这个页面,并试图使其工作,但到目前为止我还没有幸运:



stack.h

  #ifndef STACK_H 
#define STACK_H
template< class T> ;
class Stack {
public:
Stack(int n);
〜Stack(){delete [] s; };
private:
T * s;
int _top;
int _size;
};
#endif // STACK_H

stack.cpp p>

  #includestack.h
template< class T>
Stack< T> :: Stack(int n){
_size = n;
_top = -1;
s = new T [_size];
}

main.cpp
$ b

  #include< iostream> 
#includestack.h
using namespace std;
int main(){
Stack< int> s(10); //未定义的引用`Stack< int> :: Stack(int)'
return 0;
}



当我编译(gcc 4.5.2),我得到一个错误:未定义引用Stack< int> :: Stack(int)。我试过几件事,但没有任何真正的知识支持我做什么。

解决方案

在cpp中只能有一个模板类定义文件,如果它是一个专门的定义 - 即你知道 T 是什么。



这里,你的模板类的所有定义都必须放在头文件中。编译器必须知道这些每次一个新的实例被声明或定义,因为类型,从而行为,改变。 cpp文件中的定义意味着一个不同的翻译单元,所以编译器不可能知道每一个 T 的行为,你试图应用到你的模板。 p>

Possible Duplicate:
Why can templates only be implemented in the header file?

I've struggled with this for a while, and I've taken a look to several questions here, but being new to C++ I haven't been able to understand where I am wrong.

Here is the code, I took it from this page and tried to make it work, but so far I haven't been lucky:

stack.h

#ifndef STACK_H
#define STACK_H
template <class T>
class Stack {
  public:
    Stack(int n);
    ~Stack() { delete[] s; };
  private:
    T* s;
    int _top;
    int _size;
};
#endif // STACK_H

stack.cpp

#include "stack.h"
template <class T>
Stack<T>::Stack(int n) {
  _size = n;
  _top = -1;
  s = new T[_size];
}

main.cpp

#include <iostream>
#include "stack.h"
using namespace std;
int main() {
  Stack<int> s(10); // undefined reference to `Stack<int>::Stack(int)'
  return 0;
}

When I compile (gcc 4.5.2) I get one error: undefined reference to Stack<int>::Stack(int). I've tried several things but without any real knowledge to support what I do. I will be really thankful if somebody can explain me what's going on.

解决方案

You can only have a template class definition in a cpp file if it's a specialized definition - i.e. you know what T is.

Other than that, and your case belongs here, all definitions of your template class have to go in the header file. The compiler has to know about these each time a new instance is declared or defined because the type, and thus the behavior, changes. Definitions in a cpp file would mean a different translation unit, so the compiler couldn't possibly know about the behavior for every single T you try to apply to your template.

这篇关于C ++(gcc):未定义的引用`Stack&lt; int&gt; :: Stack(int)'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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