在模板 class 构造函数中创建一个计数器

Creating a counter inside a template class constructor

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

You are to create a constructor that may take the department name as an argument, and if it’s null it will ask for a department name to be entered from the keyboard and stores it. It also initializes a counter that keeps track of the number of employees in the array and is maintained when you add, remove, or clear.

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

Department.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
...

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

Is there a way to use the counter initialized in the constructor outside of the constructor without changing the argument requirements for Department?

当然可以。创建一个计数器成员变量,并在您为 class.

编写的方法中使用它
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
};