首页 > 解决方案 > 在模板类构造函数中创建计数器

问题描述

我被一个家​​庭作业问题困住了。我们要创建一个名为department的类模板,在构造函数中,我们需要初始化一个计数器以供以后使用。我无法理解如何在程序的其他地方使用这个计数器。我们提供了一个 main.cpp 文件以供使用,我们不允许更改该文件。这些是我坚持的具体说明:

您将创建一个可以将部门名称作为参数的构造函数,如果它为空,它将要求从键盘输入部门名称并存储它。它还初始化一个计数器,该计数器跟踪数组中的员工数量,并在您添加、删除或清除时​​维护。

我设法让它工作的唯一方法是将构造函数设置为接受两个参数,一个用于部门名称,一个用于计数器。但是提供的 main.cpp 文件只允许一个参数,名称。

部门.h:

template <class Type>
class Department {

  private:
    std::string name;
   ...

  public:
  Department(const std::string & deptName)
  {
    int counter = 0;
    name = deptName;
  }
... 
};

Main.cpp(已提供,不允许更改):

int main()
{   Department dept1("CIS");   // a department
...

有没有办法在构造函数之外使用在构造函数中初始化的计数器而不改变 Department 的参数要求?

标签: c++classstatic-variables

解决方案


有没有办法在构造函数之外使用在构造函数中初始化的计数器而不改变 Department 的参数要求?

当然。创建一个计数器成员变量,并在您为类编写的方法中使用它。

template <class Type>
class Department {

private:
  std::string name;
  int counter;

public:
  Department(const std::string & deptName)
  {
    counter = 0;     // note `int` not needed, as counter is already declared
    name = deptName;
  }

  int getCounter()
  {
    return counter;
  }

  void addEmployee(std::string name)
  {
    counter++;
    // do something with adding employees
  }

  // other methods
};

推荐阅读