[英]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]);
...
}
我想在運行時將值傳遞給a
和b
。 但是,上面的代碼不適用於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.