简体   繁体   English

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

[英]How to reset a static struct inside a function

So let's say I have a function所以假设我有一个功能

struct coinTypes {
    int tenP = 0;
    int twentyP = 0;
    int fiftyP = 0;
};

coinTypes numberOfCoins(int coins)
{

    static coinTypes types;

    // incrementing structs values
}

Let's say I have used this function for some time, and values in coinTypes struct are no longer 0. Then I decided to use this function for another purpose and I need the values to be 0 again.假设我已经使用这个函数有一段时间了,并且 coinTypes 结构体中的值不再是 0。然后我决定将这个函数用于另一个目的,我需要这些值再次为 0。 Is there any way to reset coinTypes struct?有没有办法重置 coinTypes 结构?

Dont use static in this case.在这种情况下不要使用静态。 Try to use: Class Coin with object params coinType, couinNumber for example.尝试使用:类 Coin 与对象参数 coinType,例如 couinNumber。

Unless you are just misunderstanding what the keyword static does (you probably are), this is what you are asking for:除非您只是误解了关键字static作用(您可能是),否则这就是您所要求的:

run online在线运行

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

Prints:印刷:

0
1
2
3
4
0
1
2
3
4

If you just want to convert int coins into britishCoins without storing it's value inside the function it's simple:如果您只想将int coins转换为britishCoins int coins而不将其值存储在函数中,则很简单:

run online在线运行

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

output:输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM