#include <stdio.h>
void func() {
static int x = 0; // x is initialized only once across three calls of
// func()
printf("%d\n", x); // outputs the value of x
x = x + 1;
}
int main(int argc, char * const argv[]) {
func(); // prints 0
func(); // prints 1
func(); // prints 2
// Here I want to reinitialize x value to 0, how to do that ? <-- this line
return 0;
}
在上面的代码中,调用 func() 3次后我想重新初始化x
为零。有什么方法可以重新初始化为0吗?
你想要这个功能吗always三次调用后重置计数器?或者您希望调用者在任意时间重置计数?
如果是前者,你可以这样做:
void func() {
static int x = 0;
printf("%d\n", x);
x = (x + 1) % 3;
}
如果是后者,使用局部静态变量可能是一个糟糕的选择;您可以使用以下设计:
class Func
{
int x;
// disable copying
public:
Func() : x(0) {}
void operator() {
printf("%d\n", x);
x = x + 1;
}
void reset() {
x = 0;
}
};
Func func;
您应该将其设置为不可复制,以避免两个对象增加两个不同的计数器(或使其成为单例),或者将计数器设置为静态成员,以便每个对象增加相同的计数器。现在你像这样使用它:
int main(int argc, char * const argv[]) {
func(); // prints 0
func(); // prints 1
func(); // prints 2
func.reset();
return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)