c++ - 在模板类构造函数中创建计数器
问题描述
我被一个家庭作业问题困住了。我们要创建一个名为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 的参数要求?
解决方案
有没有办法在构造函数之外使用在构造函数中初始化的计数器而不改变 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
};
推荐阅读
- groovy - 提取 groovy jar
- gcc - 构建 JOGL 在 c.build.nativewindow.awt 期间出现 gcc 错误:jawt.dll:文件无法识别:文件格式无法识别
- powerbi - Power BI 服务上的奇怪行为:视觉级别筛选器仅在特定页面上自动重置为“全部”
- html - 如何在 Angular Using API 中获取特定 Id 的值(CRUD In Angular Using API)
- c - 在循环中将整数作为字符串附加到 char[]
- javafx - 在 javafx 的场景生成器中未显示 css 样式
- javascript - 不使用 endsWith() 确认字符串的结尾
- javascript - 为什么 unhandledrejection 事件无法捕获 React 中的一些错误?
- loops - 我想写一个数字,然后做一个运算(如果N是偶数,那么N/2,或者如果N是奇数,那么(N*3)+1),直到新的数字等于1
- ms-access - 如何在 Access 报告中将日期显示为文本