C ++未定义的构造函数 [英] C++ undefined constructor

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

问题描述

我刚刚开始使用C ++,遇到这个问题。我在Fifo.h中定义了一个类Fifo:

I am just starting out with C++, and ran into this problem. I have a class Fifo defined in Fifo.h:

/* Fifo.h */
#ifndef FIFO_H_
#define FIFO_H_

#include <atomic>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

template <class T>
class Fifo
{
public:

   Fifo<T>(int len);
   ~Fifo<T>();

   int  AddTokens(T* buffer, int len);
   int  RetrieveTokens(T* buffer, int len);

private:
   //int len;

};

#endif /* FIFO_H_ */

cpp:

/* Fifo.cpp*/
#include "Fifo.h"

template <class T>
Fifo<T>::Fifo(int len)
{
  //_fifoptr = new FifoImpl_class((T)len);
  printf ("From the constructor\n");
  //thisbuffer = malloc(sizeof(T)*len);
}


template <class T>
Fifo<T>::~Fifo() { }

template <class T>
int Fifo<T>::AddTokens(T* buffer, int len)
{
  printf("Added tokens\n");
  return(1);
}


template <class T>
int Fifo<T>::RetrieveTokens(T* buffer, int len)
{
  printf("Removed tokens\n");
  return(2);
}

然后,我以这样的方式测试我的类(Fifotest.cpp) p>

And, I test my class like this (Fifotest.cpp):

#include "Fifo.h"
int main(int argc, char *argv[])
{
  Fifo<int> MyFifo(20);
}

使用gcc-4.5构建它会给我这个错误:
undefined引用 Fifo 未定义引用 Fifo :: Fifo(int)'

Building it with gcc-4.5 gives me this error: undefined reference to Fifo<int>::~Fifo()' undefined reference toFifo::Fifo(int)'

看起来我定义了相关的方法,但我不能弄清楚为什么我得到这个错误。我花了时间去搜索它,并且选项是采取一个运行类和修改它。但是,我想知道我已经有什么问题了。非常感谢任何帮助!

Looks like I have the relevant methods defined, but I am not able to figure out why I get this error. I spent time googling for it, and the option was to take a running class and modify it. But then, I want to know what is wrong with what I already have. Would appreciate any help!

推荐答案

2分:


  • 构造函数被错误地声明。

  • The constructor is declared erroneously.

Fifo<T>(int len); //wrong
Fifo(int len);    //right


  • 模板应在使用它们的同一翻译单元中定义,所以有单独的.h和.cpp文件通常不适用于模板(例如,参见这个问题)。请将您的cpp文件的内容移到头文件,您应该就可以了。

  • Templates should be defined in the same translation unit in which they are used, so having separate .h and .cpp files usually doesn't work for templates(see, for example, this question). Please move the contents of your cpp file to the header file and you should be fine.

    这篇关于C ++未定义的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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