c++ - 非整数常量声明 - dev-c++ - 错误 : `type' was not declared in this scope

标签 c++ constants declaration dev-c++

<分区>

我在类中有一个非整数常量声明。

我不断收到以下信息:

ComponentClass.h:14: error: template declaration of const typename ComponentClass<T> ::position NULLPOSITION
ComponentClass.h:14: error: position was not declared in this scope
ComponentClass.h:14: error: expected ; before numeric constant

请在下面找到我的代码。

组件类.h

#ifndef _ComponentClass_H
#define _ComponentClass_H

template< class T>
class ComponentClass
{
public:

       typedef ComponentClass* position;
       ComponentClass();
};

template<class T>
const typename ComponentClass<T>::position NULLPOSITION=(position)0;

template<class T>
ComponentClass<T>::ComponentClass(){}
#endif

最佳答案

您似乎在尝试定义一种“模板变量”,但 C++ 中不存在此类功能。

你也未能获得第二名的资格,你写了position在同一行代码中。

这两个因素是导致你出错的原因。


可能NULLPOSITION一些意义成为类模板实例的静态成员:

template< class T>
class ComponentClass
{
public:

       typedef ComponentClass* position;
       static const position NULLPOSITION;

       ComponentClass();
};

但是现在,据我所知,您必须为每个 T 定义它你想使用,这很糟糕:

template<>
const ComponentClass<int>::position ComponentClass<int>::NULLPOSITION =
    static_cast<ComponentClass<int>::position>(0);

template<>
const ComponentClass<double>::position ComponentClass<double>::NULLPOSITION =
    static_cast<ComponentClass<double>::position>(0);

也许改为 position比单纯的指针类型更聪明一点——让它成为一个适当的用户定义类型,带有一个默认构造函数,将对象初始化为“空”状态。例如,函数对象以这种方式工作; std::function<void()>()是一个有效但单一的函数对象。

关于c++ - 非整数常量声明 - dev-c++ - 错误 : `type' was not declared in this scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13730283/

相关文章:

c++ - 处理 map 键中指向值的常量

c# - C#'s readonly vs C++' s const - 等价物

c++ - c/c++ 中的指针

c++ - 为什么只有一个参数的可变参数模板与非可变参数模板不同?

c++ - boost 程序选项短/长参数名称

ios - 为什么加减两个#define'd 宏在 iPhone/Objective-c 上不起作用

javascript - 在 Javascript 中使用 .prototype 的原因

c++ - C++中函数调用时的编译器错误

iphone - 在我的头文件中声明方法

c++ - 超过 8 个字符的字符串会导致无限循环 C++