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

问题描述 投票:0回答:3

假设我有一个函数

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 结构吗?

c++ function struct static
3个回答
0
投票

除非您只是误解了关键字

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

0
投票

在这种情况下不要使用静态。尝试使用: 带有对象参数 coinType 的 Coin 类,例如 couinNumber。


0
投票

这就是我重置静态变量的方式:

bool MyString::toke(const MyString& src, const MyString& tgt, MyString &token) {

    uint tgt_pos;
    static MyString tmp = "default";
    static bool found = false;

    if (tmp == "default")
        tmp = src;
    else if (!tmp.length())
        tmp = src;

    // reset static tmp for next pass
    tmp = "";
}
© www.soinside.com 2019 - 2024. All rights reserved.