繁体   English   中英

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

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

我在初始化全局常量变量时​​遇到问题:

int a;
const int b = a * a;

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

我想在运行时将值传递给ab 但是,上面的代码不适用于b 那我该怎么办? 谢谢!!!

您不能,而且在使用全局变量时这是一个真正的问题,这就是为什么大多数大型系统开发人员(应该)选择不使用该功能的原因。

我最喜欢的方法:

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());
}

您可以在运行时使用像这样的静态 int 初始化它。 稍后对变量的更改会导致编译错误:

#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