简体   繁体   English

c ++如何按顺序初始化全局const变量

[英]c++ how to initialize global const variables sequentially

I have a problem with initializing global const variables:我在初始化全局常量变量时​​遇到问题:

int a;
const int b = a * a;

int main(int argc, char **argv) {
    a = std::stoi(argv[1]);
    ...
}

I would like to pass values to a and b in the runtime.我想在运行时将值传递给ab However, the above code does not work for b .但是,上面的代码不适用于b What should I do then?那我该怎么办? Thanks!!!谢谢!!!

You can't and it's a real issue when using globals, which is why most large system developers (should) opt out of using the feature.您不能,而且在使用全局变量时这是一个真正的问题,这就是为什么大多数大型系统开发人员(应该)选择不使用该功能的原因。

My favorite approach:我最喜欢的方法:

int get_global_a(int initial_value=0) {
  static int a = initial_value;
  return a;
}

int get_global_b(int a_value=0) {
  static int b = a_value * a_value;
  return b;
}

/* Make sure this is the first line you execute in your program, but not before main! */
void initialize_all_globals(/* all necessary params */) {
    int a = std::stoi(argv[1]);
    get_global_a(a);
    get_global_b(get_global_a());
}

You can initialize it with a static int like this at runtime.您可以在运行时使用像这样的静态 int 初始化它。 Later changes to the variable lead to a compile error:稍后对变量的更改会导致编译错误:

#include <iostream>

static int hidden_b;
const int& b(hidden_b);

int main(int argc,char** argv) {
    int a = std::stoi(argv[1]);
    hidden_b = a*a;
    std::cout << b << std::endl;
    //b = 3; // compile error

    // problems arise, if you change the hidden variable
    /*hidden_b = 3;
    std::cout << b << std::endl;*/
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM