简体   繁体   English

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

[英]Creating a counter inside a template class constructor

I'm stuck on a homework question. 我被困在一个家庭作业问题上。 We are to create a class template called department, and in the constructor, we need to initialize a counter to be used later. 我们将创建一个名为Department的类模板,并在构造函数中,我们需要初始化一个计数器以供以后使用。 I'm having trouble understanding how to use this counter elsewhere in the program. 我在理解如何在程序的其他地方使用此计数器时遇到麻烦。 We were provided with a main.cpp file to use, which we aren't allowed to change. 我们提供了一个main.cpp文件供您使用,我们不允许对其进行更改。 These are the specific instructions I'm stuck on: 这些是我坚持的具体说明:

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. 您将创建一个可以将部门名称作为参数的构造函数,如果为null,它将要求从键盘输入部门名称并将其存储。 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. 它还会初始化一个计数器,该计数器跟踪阵列中的雇员数量,并在您添加,删除或清除时​​维护该计数器。

The only way I've managed to get it to work is by setting the constructor to accept two arguments, one for department name, and one for the counter. 我设法使其正常工作的唯一方法是将构造函数设置为接受两个参数,一个用于部门名称,一个用于计数器。 But the main.cpp file provided only allows for one argument, name. 但是提供的main.cpp文件仅允许使用一个参数,即name。

Department.h: Department.h:

template <class Type>
class Department {

  private:
    std::string name;
   ...

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

Main.cpp (provided, and not allowed to change): 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? 有没有一种方法可以使用在构造函数之外的构造函数中初始化的计数器,而无需更改Department的参数要求?

Is there a way to use the counter initialized in the constructor outside of the constructor without changing the argument requirements for Department? 有没有一种方法可以使用在构造函数之外的构造函数中初始化的计数器,而无需更改Department的参数要求?

Sure. 当然。 Make a counter member variable, and use it in the methods you write for your 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
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM