【问题标题】:Class template instantiation error: type not declared in this scope类模板实例化错误:类型未在此范围内声明
【发布时间】:2015-07-05 05:40:33
【问题描述】:

所以我正在为一个 c++ 类编写粒子加速器代码,但我在设置我被要求使用的初始类时遇到了问题。教授希望我们在课堂上使用模板,但是当我尝试实现它们时,我收到了一些错误。例如:

#include <iostream>
#include <cmath>

using namespace std;
template <class Type>
class ThreeVector {
private:
    Type mx;
    Type my;
    Type mz;
public:
    ThreeVector();
    ThreeVector(Type x=0, Type y=0, Type z=0);


};

ThreeVector<Type>::ThreeVector() {
    Type mx=0;
    Type my=0;
    Type mz=0;
}
ThreeVector<T>::ThreeVector(Type x, Type y, Type z) {
    mx=x;
    my=y;
    mz=z;
}

是我的头文件的一部分(该类必须在头文件中)。当我运行我的程序时(如果需要可以提供),它给了我以下错误:

ThreeVector.h:30:13: 错误:“类型”未在此范围内声明

ThreeVector.h:30:17: 错误:模板参数 1 无效

ThreeVector.h:在函数“int ThreeVector()”中: ThreeVector.h:30:32: 错误:'int ThreeVector()' 重新声明为不同类型的符号

ThreeVector.h:6:7: 注意:之前的声明‘template class ThreeVector’

ThreeVector.h:31:2: 错误:“类型”未在此范围内声明

ThreeVector.h:32:7: 错误:在“我的”之前需要“;”

ThreeVector.h:33:7: 错误:在“mz”之前需要“;”

ThreeVector.h:在全局范围内: ThreeVector.h:35:13: 错误:“类型”未在此范围内声明

在我开始使用模板之前,这些问题并不存在,也就是说,如果我明确定义所有变量类型,我的类就可以正常工作。所以,我不太确定我的模板定义有什么问题?如果有人可以提供帮助,我将不胜感激。

谢谢!

【问题讨论】:

  • 如果没有参数,应该调用哪个构造函数?
  • 尝试将template&lt;class T&gt;放在类外声明的方法前面。 (用模板参数中的任何说明符替换 T。)
  • 抱歉,快速更正:ThreeVectoor 的一个实例已更改为 ThreeVector.. 另外,模板 不是已经在类外声明了吗?
  • template&lt;...&gt; 仅适用于紧随其后的声明或定义。
  • 我不知道。谢谢你的澄清,克里斯,它现在似乎工作了!

标签: c++ templates compiler-errors


【解决方案1】:
  1. 你忘了添加

    template <typename Type>
    

    在函数定义之前。

  2. 从函数体中删除Type。当您添加Type 时,您声明了三个与类成员无关的函数变量。

template <typename Type>
ThreeVector<Type>::ThreeVector() {
    mx=0;
    my=0;
    mz=0;
}

您可以通过使用初始化列表语法初始化成员来使其变得更好:

template <typename Type>
ThreeVector<Type>::ThreeVector() : mx(0), my(0), mz(0) { }

【讨论】:

  • 我们没有被介绍过初始化列表语法,它与我上面发布的代码到底有什么不同?只是想更好地理解以备将来使用!
  • @RossBauer,它初始化成员,而不是进行默认初始化,然后再分配给它们。后者甚至在所有情况下都不起作用,比如它是一个没有默认构造函数的类。
【解决方案2】:

您必须为属于模板类但在类定义之外定义的方法声明模板参数。所以要定义你的函数,你必须这样做:

template<class Type>
ThreeVector<Type>::ThreeVector() {
    mx=0;
    my=0;
    mz=0;
}

template<class Type>
ThreeVector<T>::ThreeVector(Type x, Type y, Type z) {
    mx=x;
    my=y;
    mz=z;
}

这是因为当方法声明在类定义之外时,模板化类型不可用于方法声明。要解决此问题,您必须添加一个 template&lt; ... &gt;,其参数与原始类相同。

此外,您应该使用初始化列表来初始化成员。这将使您的构造函数看起来像这样:

template<class Type>
ThreeVector<Type>::ThreeVector() : 
    mx(0),
    my(0),
    mz(0)
{

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-15
    • 1970-01-01
    • 1970-01-01
    • 2012-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多