在C++中的类中累积变量

accumulate variables in a class in C++

本文关键字:变量 C++      更新时间:2023-10-16

我有一个类,它有一些成员函数,我想累积并保持值。这就是我的主要内容:

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