模板类中的静态const成员初始化

static const member inizialitazion in template class

本文关键字:const 成员 初始化 静态      更新时间:2023-10-16

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