C++ 模板类中构造函数的语法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10939242/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:38:39  来源:igfitidea点击:

Syntax for constructor in template class

c++templatescompiler-errors

提问by xst

I am trying to create a generic circular buffer template but there is some syntax error that I cannot understand. The error is in my constructor, though it seems I've parameterized the destructor in the same way and that one works. I've followed the example in Stroustrup C++, and he uses a parameter before the scope resolution operator and also in the function name, just as I have. I'm also certain there are no circular dependencies because I'm only compiling one file. Also the implementation and declarations are in the same file (CircBuf.h) and there is no corresponding .cpp file, so linking should not be an issue either. I've tried adding the "inline" keyword as per thissolution and I get the same error.

我正在尝试创建一个通用的循环缓冲区模板,但存在一些我无法理解的语法错误。错误出在我的构造函数中,尽管我似乎以相同的方式参数化了析构函数并且该方法有效。我遵循了 Stroustrup C++ 中的例子,他在作用域解析运算符之前和函数名中使用了一个参数,就像我一样。我也确定没有循环依赖,因为我只编译一个文件。此外,实现和声明在同一个文件 (CircBuf.h) 中,并且没有相应的 .cpp 文件,因此链接也不应该成为问题。我已尝试根据解决方案添加“inline”关键字,但出现相同的错误。

/* CircBuf.h */
template<typename T> class CircBuf {
  // don't use default ctor                                                                                                                                               
  CircBuf();

  int size;
  T *data;
public:
  CircBuf(int);
  ~CircBuf();
};

template<typename T> CircBuff<T>::CircBuf<T>(int i) {
  data = new T[i];
}
template<typename T> CircBuf<T>::~CircBuf<T>() {
  delete data;
}

makefile

生成文件

all:
        g++ -g -pedantic CircBuf.h -o prog

compiler-error

编译器错误

CircBuf.h:13:22: error: ‘CircBuff' does not name a type

回答by K-ballo

CircBuffcertainly does not name a type, the name of the type you intended is CircBufwith a single f.

CircBuff当然不会命名类型,您想要的类型的名称CircBuf带有单个f.

Note that you also need to lose the trailing <T>on both constructor and destructor.

请注意,您还需要丢失<T>构造函数和析构函数的尾随。