Can I initialize a static const member at run-time in C++?(我可以在 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.
推荐答案
很抱歉,我不同意在程序中初始化 static 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");
如您所见,这些静态常量在编译时不一定是已知的.它们可以从环境中设置,例如配置文件.
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 成员吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我可以在 C++ 运行时初始化静态 const 成员吗?
基础教程推荐
- Windows Media Foundation 录制音频 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07