我不知道这是否可能。从我看到的所有示例来看,数组都是在{ }括号内定义的,但在我的例子中,这是不太可能的。
我想要做的是保持这个在我的绘图功能,以绘制多个圆圈,缓慢增长的大小。
我通过使用调试器得到的是,每次循环命中时,静态数组都会被重置。
我也尝试过像static Rect rc[5] = {}这样的东西
void fun_called_every_five_seconds() {
static Rect rc[5];
for (int i = 0; i < count; i++) {
int x = rand()%400;
int y = rand()%400;
int r = rand()%200;
rc[i] = Rect (x,y,r,r);
}
rc[0].X += 50;
// I check value of rc[0].X right here
}发布于 2017-02-06 14:29:37
每次循环命中时,静态数组都会被重置。
是的,您的循环显式地重置了静态数组。
最小的更改是只运行一次初始化循环:
void for_fun_called_every_five_seconds() {
static Rect rc[5];
static bool init = false;
if (!init) { // this only happens once
init = true;
for (int i = 0; i < count; i++) {
int x = rand()%400;
int y = rand()%400;
int r = rand()%200;
rc[i] = Rect (x,y,r,r);
}
}
rc[0].X += 50;
// I check value of rc[0].X right here
}但这是相当丑陋的,不必要的难以推理。更喜欢像
class Circles {
Rect rc[5];
public:
Circles() {
for (int i = 0; i < count; i++) {
int x = rand()%400;
int y = rand()%400;
int r = rand()%200;
rc[i] = Rect (x,y,r,r);
}
}
void for_fun_called_every_five_seconds() {
// should this also be in a loop,
// ie. each rc[i] gets increased?
rc[0].X += 50;
// I check value of rc[0].X right here
}
};发布于 2017-02-06 15:12:26
您可以拆分代码并将数组初始化放在其他地方:
auto make_rect_array() {
std::array<Rect, 5> rc;
for (int i = 0; i < count; i++) {
int x = rand()%400; // you may want better random
int y = rand()%400;
int r = rand()%200;
rc[i] = Rect (x,y,r,r);
}
return rc;
}然后,在您的函数中调用它:
void fun_called_every_five_seconds() {
static auto rc = make_rect_array();
rc[0].X += 50;
// I check value of rc[0].X right here
}这样,您就不会在代码中引入额外的分支,它看起来更干净,而且线程安全。
发布于 2017-02-06 14:33:31
这里没什么好惊讶的。每次调用一个函数时,它的所有代码都是从它的参数执行的。这里唯一的例外是static变量的初始化,它保证在程序生存期内只运行一次(自C++11以来也是线程安全的)。一个变量的初始化只在它的定义过程中进行,在这个上下文中,在您给变量命名的那一行上。之后的所有代码只是“变异”您的变量,以给它您想要的值:它不是初始化。
这里有两个解决方案。或者使用std::call_once和lambda (参见once)使“初始化”代码只运行一次。或者,在变量的定义中,您可以将所有这些代码放在一行中。对于C风格的数组来说,这可能比较复杂,但对于std::array来说则不然,它可以很容易地从函数返回并用于初始化std::array。
std::array<Rect, 5> initialize_rc() {
std::array<Rect, 5> rc;
for (int i = 0; i < count; i++) {
int x = rand()%400;
int y = rand()%400;
int r = rand()%200;
rc[i] = Rect (x,y,r,r);
}
return rc;
}
void for_fun_called_every_five_seconds() {
static std::array<Rect, 5> rc = initialize_rc();
rc[0].X += 50;
// I check value of rc[0].X right here
}https://stackoverflow.com/questions/42069909
复制相似问题