0
#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?

4

3 回答 3

2

Do you want the function always to reset the counter after three invocations? or do you want to the caller to reset the count at arbitrary times?

If it is the former, you can do it like this:

void func() {
  static int x = 0;
  printf("%d\n", x);
  x = (x + 1) % 3;
}

If it is the latter, using a local static variable is probably a bad choice; you could instead use the following design:

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;

You should make it either non-copyable to avoid two objects increasing two different counters (or make it a singleton), or make the counter a static member, so that every object increments the same counter. Now you use it like this:

int main(int argc, char * const argv[]) {
  func(); // prints 0
  func(); // prints 1
  func(); // prints 2

  func.reset();
  return 0;
}
于 2012-10-29T08:06:24.843 回答
1

您可以func()将变量的地址分配给从外部可见的指针func()

或者你可以有一个特殊的参数,你可以传递给func()它来告诉它重置变量。

但实际上,声明xinside的全部意义func()在于使其仅在func(). 如果您希望能够修改x,请在其他地方定义它。x由于您正在编写 C++,因此成为某个类的静态成员可能是有意义的。

于 2012-10-29T07:24:40.917 回答
0

你不能。这是一个在外部不可见的局部静态变量func()

您可以使用:

  1. 全局静态(一般不推荐)。
  2. 通过引用/指针参数传递它,或通过引用返回。
于 2012-10-29T07:18:44.423 回答