use*_*212 21 c++ static initialization const
是否可以在运行时初始化我的类的静态const成员?这个变量在我的程序中是一个常量,但我想将它作为命令行参数发送.
//A.h
class A {
public:
static const int T;
};
//in main method
int main(int argc,char** argv)
{
//how can I do something like
A::T = atoi(argv[1]);
}
Run Code Online (Sandbox Code Playgroud)
如果无法做到这一点,我应该使用的变量类型是什么?我需要在运行时初始化它以及保留常量属性.
das*_*ght 30
在main开始初始化static变量之后,您不能依赖于生成的数据,因为转换单元中的静态初始化在获得控制main之前发生main,而其他转换单元中的静态初始化可能main在未指定顺序的静态初始化转换单元之前或之后发生.
但是,您可以初始化隐藏的非const变量,并提供const对它的引用,如下所示:
struct A {
public:
// Expose T as a const reference to int
static const int& T;
};
//in main.cpp
// Make a hidden variable for the actual value
static int actualT;
// Initialize A::T to reference the hidden variable
const int& A::T(actualT);
int main(int argc,char** argv) {
// Set the hidden variable
actualT = atoi(argv[1]);
// Now the publicly visible variable A::T has the correct value
cout << A::T << endl;
}
Run Code Online (Sandbox Code Playgroud)
A.S*_*S.H 11
我很遗憾不同意这些评论和答案,表示static const在程序启动时而不是在编译时初始化符号是不可能的.
实际上这是可能的,我使用了很多次,但我从配置文件初始化它.就像是:
// GetConfig is a function that fetches values from a configuration file
const int Param1 = GetConfig("Param1");
const int MyClass::Member1 = GetConfig("MyClass.Member1");
Run Code Online (Sandbox Code Playgroud)
如您所见,这些静态consts在编译时不一定是已知的.它们可以从环境中设置,例如配置文件.
另一方面,如果可行的话,从argv []设置它们似乎非常困难,因为当main()启动时,静态符号已经初始化.
不,你做不到.
如果无法做到这一点,我应该使用哪种变量?
您可以使用非const会员.
class A
{
public:
static int T;
};
int A::T;
Run Code Online (Sandbox Code Playgroud)
另一个选择是创建T一个私有成员,结交main朋友,只有它可以修改该值,然后通过一个函数公开该成员.
#include <cstdlib>
class A
{
public:
static int getT() { return T; }
private:
static int T;
friend int main(int argc, char** argv);
};
int A::T;
int main(int argc, char** argv)
{
A::T = std::atoi(argv[1]);
return 0;
}
Run Code Online (Sandbox Code Playgroud)