初始化头文件中声明的静态变量

Initialize static variables declared in header

本文关键字:静态 变量 声明 文件 初始化      更新时间:2023-10-16

我正在为一个公司项目更改一个大型类的类实现,该项目将几个静态变量声明为类的私有成员。在类头文件中声明的许多数组和结构体都利用了这些静态变量。现在我需要以某种方式从主函数中分配静态数据成员值。我尝试通过构造函数赋值静态变量,但头文件在构造函数调用之前声明,所以这是不可能的。

例如,如果我有

class Data
{
private:
  static unsigned int numReadings = 10;
  static unsigned int numMeters = 4;
  unsigned int array[numMeters];
}

我想改变它,这样我就可以设置numreads和numMeters从我的主函数以某种方式,所以它将允许我所有的数组和结构体利用numMeters和numreads被正确初始化。

在c++中有办法做到这一点吗?当然,我总是可以改变我的类设计,并以某种方式在构造函数中设置这些,但如果可以的话,我希望避免这样做,因为这会花费相当长的时间。

您不能在 main函数中执行,但是您可以在main.cpp文件中执行:

// Main.cpp
#include <iostream>
#include "T.h"
using namespace std;
int T::a = 0xff;
int main()
{
   T t; // Prints 255
   return 0;
}
// T.h
#pragma once
#include <iostream>
using namespace std;
class T {
public:
    T() { cout << a << endl; }
private:
    static int a;
};

您是否尝试过将它们公开并使用Data:: numreads = 10访问它们?

更新:

#include <cstdlib>
using namespace std;
/*  *   */
class Asdf
{
public:
    static int a;
};
int Asdf::a = 0;
int main(int argc, char** argv) {
    Asdf::a = 2;
    return 0;
}

无论这些变量的可访问性如何,您都需要在类定义之外定义和初始化静态成员:

// header
class Data
{
private:
  static unsigned int numReadings;
  static unsigned int numMeters;
  unsigned int array[numMeters];  //<=see edit
}; 
// class implementation file
unsigned int Data::numReadings = 10;
unsigned int Data::numMeters = 4;

这是类实现的一部分,不应该出现在头文件中(ODR规则)。

当然,如果您希望从外部访问这些变量(在类的所有实例之间共享),则需要将它们设为public,或者更好的做法是,将它们设为预见和访问器。编辑:

由于问题是围绕静态问题制定的,我没有注意到可变长度数组:这不是标准的c++,尽管一些编译器可能会接受它作为非标准扩展。

要正确地做到这一点,您应该定义一个vector并在构造时初始化它:
class Data
{
public: 
  Data ();
private:
  static unsigned int numReadings;
  static unsigned int numMeters;
  vector<unsigned int> mycontainer;       //<=for dynamic size 
}; 
Data::Data() : mycontainer(numMeters) { }  // initialize object with right size