这是头文件:employee.h
#ifndef EMPLOYEE_H #define EMPLOYEE_H #include#include using namespace std; class Employee { public: Employee(const string &first, const string &last)
重载的构造函数
: firstName(first),
firstName重载的构造函数
lastName(last)
lastName重载的构造函数
{ //The constructor start ++counter;
它为每个创建的对象增加一个加号;
cout << "Employee constructor for " << firstName << ' ' << lastName << " called." << endl; } ~Employee() {
析构函数cout <<"~Workee()调用"<< firstName <<"<< lastName << endl;
返回每个对象的名和姓
--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#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;
原因是在头文件中放置这样的初始化会在包含头的每个地方复制初始化代码.