初始化头文件中声明的静态变量
Initialize static variables declared in header
我正在为一个公司项目更改一个大型类的类实现,该项目将几个静态变量声明为类的私有成员。在类头文件中声明的许多数组和结构体都利用了这些静态变量。现在我需要以某种方式从主函数中分配静态数据成员值。我尝试通过构造函数赋值静态变量,但头文件在构造函数调用之前声明,所以这是不可能的。
例如,如果我有
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
相关文章:
- 在 .h 文件中的类中声明静态变量和在.cpp文件中声明"global"变量有什么区别
- 模板基类中的静态变量
- 类和静态变量
- 不同作用域中的静态变量和全局变量
- 静态变量声明和定义
- 是否可以依赖函数范围的静态变量来执行程序关闭期间调用的方法?
- 在类中继承静态变量?
- "local scope"中的 C++ 初始化静态变量
- 使用静态变量的递归调用的不同输出
- 复制文件流C++静态变量
- 跨模板化函数编译的静态变量
- C++编译器是否优化了顺序静态变量读取?
- C++,每个循环初始化一个新的静态变量
- (为什么)我们可以在初始化中将非静态类成员分配给静态变量吗?
- 这些语句是否等效(静态变量、常量变量和泛型)
- 程序如何知道静态变量是否需要初始化?
- 类外的静态变量实例化
- 无法解析静态变量
- 函数局部静态变量:从性能角度来看的优点/缺点
- 访问从 CPP 文件到其他头文件的静态变量