如何重置函数内部的静态结构
How to reset a static struct inside a function
假设我有一个函数
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。
相关文章:
- 静态结构和一个定义规则
- 类的静态结构指针声明在C++
- 无法使用 strcpy 将字符串复制到静态结构成员
- 'class MyClass' 在尝试定义静态结构实例时不会命名类型
- constexpr静态结构类成员的声明冲突
- C 98如何在标题中初始化静态结构阵列
- C 类静态结构成员定义
- C++中静态结构的初始化
- 有没有办法将数组行为作为静态结构数据成员?
- C++静态结构类型成员初始化
- 类内定义的静态结构的静态成员的编译时默认值
- 从具有静态结构的基类派生
- 从静态函数访问非静态结构
- 匿名命名空间中的静态结构
- C++静态结构init-item没有命名类型
- 静态结构-定义、对象、成员
- 静态结构和正常结构的区别是什么
- 如何重置函数内部的静态结构
- c++中的静态结构和静态全局变量
- c++静态结构模板方法返回枚举类型