在模板类构造函数中创建计数器

问题描述 投票:0回答:1

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

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

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

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

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

c++ class static-variables
1个回答
3
投票

有没有办法在构造函数之外的构造函数中使用初始化的计数器而不更改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
};
© www.soinside.com 2019 - 2024. All rights reserved.