如何重置函数内部的静态结构

How to reset a static struct inside a function

本文关键字:静态 结构 内部 何重置 函数      更新时间:2023-10-16

假设我有一个函数

struct coinTypes {
    int tenP = 0;
    int twentyP = 0;
    int fiftyP = 0;
};
coinTypes numberOfCoins(int coins)
{
    static coinTypes types;
    // incrementing structs values
}

假设我已经使用这个函数一段时间了,coinTypes结构中的值不再是0。然后我决定将这个函数用于另一个目的,并且我需要值再次为0。有什么方法可以重置coinTypes结构吗?

除非你只是误解了关键字static的作用(你可能是),否则这就是你想要的:

在线运行

#include <iostream>
struct britishCoins {
    int tenP;
    int twentyP;
    int fiftyP;
};
britishCoins& getCoins () {
    static britishCoins coins {0, 0, 0};
    return coins;
}
void resetCoins () {
    getCoins() = {0, 0, 0};
}
britishCoins numberOfCoins(int coins)
{
    britishCoins& result = getCoins();
    result.tenP += coins / 10;
    //...
    return result;
}
int main () {
    std::cout << numberOfCoins(0).tenP << std::endl;
    std::cout << numberOfCoins(10).tenP << std::endl;
    std::cout << numberOfCoins(10).tenP << std::endl;
    std::cout << numberOfCoins(10).tenP << std::endl;
    std::cout << numberOfCoins(10).tenP << std::endl;
    resetCoins();
    std::cout << numberOfCoins(0).tenP << std::endl;
    std::cout << numberOfCoins(10).tenP << std::endl;
    std::cout << numberOfCoins(10).tenP << std::endl;
    std::cout << numberOfCoins(10).tenP << std::endl;
    std::cout << numberOfCoins(10).tenP << std::endl;
    return 0;
}

打印:

0
1
2
3
4
0
1
2
3
4

如果您只想将int coins转换为britishCoins,而不将其值存储在函数中,那么很简单:

在线运行

#include <iostream>
struct britishCoins {
    int tenP;
    int twentyP;
    int fiftyP;
};
britishCoins numberOfCoins(int coins)
{
    britishCoins result;
    result.fiftyP = coins / 50;
    coins %= 50;
    result.twentyP = coins / 20;
    coins %= 20;
    result.tenP = coins / 10;
    return result;
}
int main () {
    for (int i = 0; i < 3; ++i) {
        britishCoins coins = numberOfCoins(130);
        std::cout << coins.fiftyP << "*50 + " << coins.twentyP << "*20 + " << coins.tenP << "*10" << std::endl;
    }
    return 0;
}

输出:

2*50 + 1*20 + 1*10
2*50 + 1*20 + 1*10
2*50 + 1*20 + 1*10

在这种情况下不要使用static。尝试使用:类Coin,对象参数为coinType,例如couinNumber。