在文件 SomeClass.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;
}
基本上我有一个带有静态常量成员 (NULLPOSITION)
的模板化类。
我已经尝试了类的 inizialitazion,在类定义之外和内联
如
static const heapPosition NULLPOSITION=-1;
声明成员时。
然而,在这两种情况下,当我在 SomeMethod
中引用时,它的值是一些随机值 - 即它还没有被初始化。
这种事情我做过很多次,从来没有遇到过这种问题。
我做错了什么?
有人可以帮帮我吗?非常感谢您抽出宝贵时间。
谢谢, 杰拉尔德塞伦特
最佳答案
你确定这是一个随机值吗?您已经声明了您的 NULLPOSITION
作为unsigned
, 所以分配它 -1
会导致cout.operator<<
(在 unsigned
重载中调用)打印一些大值( 4294967295
对于 32 位 int
)
关于c++ - 模板类中的静态常量成员初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16390185/