这是头文件:employee.h
#ifndef EMPLOYEE_H
#define EMPLOYEE_H
#include <iostream>
#include <string>
using namespace std;
class Employee {
public:
Employee(const string &first, const string &last)
重载的构造函数
: firstName(first),
名字重载的构造函数
lastName(last)
姓氏重载的构造函数
{ //The constructor start
++counter;
每个创建的对象加一个加号;
cout << "Employee constructor for " << firstName
<< ' ' << lastName << " called." << endl;
}
~Employee() {
析构函数cout <
返回每个对象的名字和姓氏
--counter;
计数器减一
}
string getFirstName() const {
return firstName;
}
string getLastName() const {
return lastName;
}
static int getCount() {
return counter;
}
private:
string firstName;
string lastName;
static int counter = 0;
这里是我得到错误的地方。但是,为什么呢?
};
主要程序:employee2.cpp
#include <iostream>
#include "employee2.h"
using namespace std;
int main()
{
cout << "Number of employees before instantiation of any objects is "
<< Employee::getCount() << endl;
这里是从类中调用计数器的值
{
开始新的作用域块
Employee e1("Susan", "Bkaer");
从Employee类初始化e1对象
Employee e2("Robert", "Jones");
从Employee类初始化e2对象
cout << "Number of employees after objects are instantiated is"
<< Employee::getCount();
cout << "\n\nEmployee 1: " << e1.getFirstName() << " " << e1.getLastName()
<< "\nEmployee 2: " << e2.getFirstName() << " " << e2.getLastName()
<< "\n\n";
}
结束范围块
cout << "\nNUmber of employees after objects are deleted is "
<< Employee::getCount() << endl; //shows the counter's value
} //End of Main
是什么问题?我不知道怎么了我一直在想很多,但是我没有错。
counter
的初始化不能在头文件中。
将头文件中的行更改为
static int counter;
并将以下行添加到employee.cpp:
int Employee::counter = 0;
原因是,将这样的初始化放在头文件中将在包含头的每个位置复制该初始化代码。
根据a similar SO answer,还有另一种方法,特别适合您当前的实现(仅标头库):
// file "Employee.h"
#ifndef EMPLOYEE_H
#define EMPLOYEE_H
class Employee {
public:
Employee() {
getCounter()++;
}
~Employee() {
getCounter()--;
}
static auto getCount() -> std::size_t {
return getCounter();
}
private:
// replace counter static field in class context,
// with counter static variable in function context
static auto getCounter() -> std::size_t& {
static std::size_t counter = 0;
return counter;
}
};
#endif //EMPLOYEE_H
我随意使用std::size
表示非负员工人数,并使用std::size
表示职能。
伴随测试(trailing return syntax):
ideone link
似乎很愚蠢,因为应该将静态类变量及其类方法和常量加载到堆上(可写空间除外),并对其进行初始化,就像自从时间开始以来一样,在程序加载时设置并链接全局和静态全局变量。我猜ISO C ++是委员会编写的代码?