模板类中的静态const成员初始化
static const member inizialitazion in template class
In file somecclass .h
#ifndef SOME_CLASS_H_
#define SOME_CLASS_H_
#include <iostream>
using std::cout;
using std::endl;
template <class T, class P>
class SomeClass
{
public:
SomeClass();
void SomeMethod();
protected:
typedef unsigned int heapPosition;
heapPosition someVariable;
private:
static const heapPosition NULLPOSITION;
};
template <class T, class P>
const typename SomeClass<T,P>::heapPosition SomeClass<T,P>::NULLPOSITION = -1;
template <class T, class P>
SomeClass<T,P>::SomeClass(){}
template <class T, class P>
void SomeClass<T,P>::SomeMethod()
{
someVariable=NULLPOSITION;
cout<<"NULLPOSITION:"<<NULLPOSITION<<endl;
}
#endif
main.cpp文件
#include <cstdlib>
#include <iostream>
#include "SomeClass.h"
using namespace std;
int main(int argc, char *argv[])
{
SomeClass<int,int> someClass;
someClass.SomeMethod();
system("PAUSE");
return EXIT_SUCCESS;
}
基本上我有一个模板类与静态const成员(NULLPOSITION)
。我已经尝试了类的初始化,包括外部类定义和内联如
static const heapPosition NULLPOSITION=-1;
声明成员。
然而,在这两种情况下,当我在SomeMethod
中引用它的值是一些随机值-即它没有被初始化。
这类事情我已经做过很多次了,从来没有遇到过这种问题。
我做错了什么?
有人能帮帮我吗?非常感谢您的宝贵时间。谢谢,杰拉尔德Celente
您确定它是一个随机值吗?您已经将NULLPOSITION
声明为unsigned
,因此将其指定为-1
将导致cout.operator<<
(在unsigned
过载中调用)打印一些大值(4294967295
为32位int
)
您需要:
template <class T, class P>
const typename SomeClass<T, P>::heapPosition SomeClass<T, P>::NULLPOSITION = -1;
或只是:
template <class T, class P>
const unsigned int SomeClass<T, P>::NULLPOSITION = -1;
(这需要放到头文件中)
然而,更好的方法是在类定义中添加初始化式:private:
static const heapPosition NULLPOSITION = -1;
这样,您就可以完全不定义变量(只要它不是odr使用)。
问题是您将NULLPOSITION
声明为unsigned int
并将其分配为-1
相关文章:
- 不允许运算符 const 参数调用 const 成员函数
- c++ 是否保证标头初始化的静态 const 成员跨编译单元和库共享单个实例?
- 在类声明中初始化 const 成员变量时在调试模式下出现异常
- 如何避免将 const 和非 const 成员函数输入到模板中的代码重复
- 初始化 const 成员的正确方法
- 使用 Boost 对具有 const 成员的类进行序列化
- 非常量调用 const 成员函数失败,只读位置C++
- PIMPL类的设置应该是const成员函数
- 与其他静态const成员初始化静态常量成员
- decltype 不会推断 const 对象的 const 成员
- 如何初始化不是静态的const成员
- 如何使用常量变量初始化类的 const 成员变量
- 使用模板参数初始化静态 const 成员
- 与const成员配对的向量
- 通过参考const成员通过参考时,尝试引用已删除的函数
- const成员初始化之前的用法是GCC和Clang的这种预期行为
- 通过const成员变量访问内联函数
- 与const成员一起安排新的和班级的分配
- 在const函数中调用非CONST成员的非const函数
- 为什么即使对于 "copy on write" 的 const 成员函数也返回一个代理类?