我可以在C ++的运行时初始化一个静态const成员吗? [英] Can I initialize a static const member at run-time in C++?

查看:113
本文介绍了我可以在C ++的运行时初始化一个静态const成员吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在运行时初始化我的类的静态const成员?这个变量在我的程序中是一个常量,但我想把它作为一个命令行参数发送。

Is it possible to initialize a static const member of my class during run-time? This variable is a constant throughout my program but I want to send it as a command-line argument.

//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]);
}



如果不能这样做,我应该使用什么类型的变量?我需要在运行时初始化它,以及保留常量属性。

If this cannot be done, what is the type of variable I should use? I need to initialize it at run-time as well as preserve the constant property.

推荐答案

很抱歉,不同意评论和回答说,不可能有 const 符号在程序启动时而不是在编译时初始化。

I am sorry to disagree with the comments and answers saying that it is not possible for a static const symbol to be initialized at program startup rather than at compile time.

实际上这是可能的,我使用了很多次,从配置文件初始化它。类似:

Actually this IS possible, and I used it many times, BUT I initialize it from a configuration file. Something like:

// GetConfig is a function that fetches values from a configuration file
const int Param1 = GetConfig("Param1");
const int MyClass::Member1 = GetConfig("MyClass.Member1");

正如你所看到的,这些静态const在编译时不一定是已知的。

As you see, these static consts are not necessarily known at compile time. They can be set from the environment, such as a config file.

另一方面,如果可行的话,从argv []中设置它们似乎非常困难,因为当main()启动时,静态符号已经初始化。

On the other hand, setting them from argv[], seems very difficult, if ever feasible, because when main() starts, static symbols are already initialized.

这篇关于我可以在C ++的运行时初始化一个静态const成员吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆