1

在文件 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;
}

基本上我有一个带有静态 const 成员的模板类(NULLPOSITION)。我已经尝试了类的 inizialitazion,包括类定义之外和内联,如

static const heapPosition NULLPOSITION=-1;

声明成员时。

然而,在这两种情况下,当我引用SomeMethod它的值时,它的值是一些随机值——即它还没有被初始化。

这种事情我做过很多次了,从来没有遇到过这种问题。

我究竟做错了什么?

有人能帮帮我吗?非常感谢您抽出宝贵时间。

谢谢,杰拉德·塞伦特

4

3 回答 3

2

你需要:

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。)

于 2013-05-05T23:32:48.877 回答
2

问题是您声明NULLPOSITIONunsigned int分配它-1

于 2013-05-05T23:45:04.180 回答
2

你确定这是一个随机值吗?您已经声明了NULLPOSITIONas unsigned,因此分配它-1会导致(在重载中cout.operator<<调用)打印一些大值(对于 32bit )unsigned4294967295int

于 2013-05-05T23:46:28.950 回答