gpt4 book ai didi

c++ - 如何从外部函数更改局部静态变量值

转载 作者:行者123 更新时间:2023-11-28 03:29:02 54 4
gpt4 key购买 nike

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

最佳答案

您是否希望函数始终 在三次调用后重置计数器?或者你想让调用者在任意时间重置计数?

如果是前者,可以这样做:

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

关于c++ - 如何从外部函数更改局部静态变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13117372/

54 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com