在C++中的类中累积变量
accumulate variables in a class in C++
我有一个类,它有一些成员函数,我想累积并保持值。这就是我的主要内容:
Class();
displayLogo();
char choice;
Class score;
cout << "1. Which of these is the coolest?" << endl
<< "a. Bowties" << endl
<< "b. Converse sneakers" << endl
<< "c. Leather jackets" << endl;
cin >> choice;
switch(choice){
case 'a': score.setA(1);
break;
case 'b': score.setB(1);
break;
case 'c': score.setC(1);
break;
}
对于每个成员函数,我希望每次做出特定选择时都能累积一个数字,并使其保持值。最后,A、B和C都应该有一个值,我可以从中找到最高值。
如何使每个成员函数累积并保持其值?
假设需求需要为此使用一个类,那么直接的方法就是将每个字母的计数存储为给定实例状态的一部分。简单示例:
class score_counter
{
int a, b, c;
public:
score_counter() : a(), b(), c() {}
void countA() { ++a; }
void countB() { ++b; }
void countC() { ++c; }
int A() const { return a; }
int B() const { return b; }
int C() const { return c; }
};
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 将数组的地址分配给变量并删除
- 为"adjacent"变量赋值时出现问题
- enum是C++中的宏变量还是整数变量
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 用C++中的一个变量定义一个常量
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 你能重载对象变量名本身返回的内容吗
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 尝试通过多个向量访问变量时,向量下标超出范围
- 试图让变量检查数组中的某些内容
- Cpp-Tuple使用带有变量的get
- 将包含C样式数组的对象初始化为成员变量(C++)
- 当vector是tje全局变量时,c++中vector的内存管理
- 通过多个头文件使用常量变量
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 执行函数时导致崩溃的变量
- 变量没有改变?通过向量的函数调用