我在类中有一个非整数常量声明。
我一直得到以下内容:
ComponentClass.h:14:错误:
const typename ComponentClass<T> ::position NULLPOSITION
的模板声明
ComponentClass.h:14:错误:未在此范围内声明位置
ComponentClass.h:14:错误:在数字常量之前预期;
请在下面找到我的代码。
ComponentClass.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
答案 0 :(得分:3)
您似乎试图定义一种“模板变量”,但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);
比仅仅指针类型更聪明 - 让它成为一个正确的用户定义类型,其默认构造函数将对象初始化为“null”状态。例如,函数对象以这种方式工作; position
是一个有效的单数函数对象。
答案 1 :(得分:0)
您看到此错误的原因是position
不在表达式(position)0
的范围内。你可以完全省略演员表(即0
)。如果您想要加入它,则需要像typename ComponentClass<T>::position
的定义一样使用NULLPOSITION
。
您似乎在定义一个静态成员变量,而没有先在类中声明它,如下所示:
static const position NULLPOSITION;
然后你可以像现在一样在课外定义它。但是,为了避免冗余定义,典型的解决方案如下:
// ComponentBase.h
class ComponentBase {
public:
typedef ComponentBase* position;
static const position NULLPOSITION;
};
// ComponentClass.h
template<class T>
class ComponentClass : public ComponentBase { ... };
// ComponentBase.cpp
const ComponentBase::position ComponentBase::NULLPOSITION = 0;
也就是说,不要让NULLPOSITION
成为ComponentClass
的每个实例化的成员,而是让所有ComponentClass
个实例共享一个定义。