错误:ISO C++禁止在类内初始化非const的静态成员。
错误:ISO C++禁止在类内初始化非const的静态成员。
这是头文件: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), lastName(last) { //构造函数开始 ++counter; //每创建一个对象,计数器加一 cout << "Employee constructor for " << firstName << ' ' << lastName << " called." << endl; } ~Employee() { //析构函数 cout << "~Employee() called for " << 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; //这里出错了,但是为什么呢? }; #endif
主要程序:employee2.cpp
#include#include "employee2.h" using namespace std; int main() { cout << "在实例化任何对象之前的员工数量为 " << Employee::getCount() << endl; //从类中调用计数器的值 { Employee e1("Susan", "Bkaer"); //从Employee类初始化e1对象 Employee e2("Robert", "Jones"); //从Employee类初始化e2对象 cout << "在实例化对象之后的员工数量为" << Employee::getCount(); cout << "\n\nEmployee 1: " << e1.getFirstName() << " " << e1.getLastName() << "\nEmployee 2: " << e2.getFirstName() << " " << e2.getLastName() << "\n\n"; } cout << "\n在删除对象之后的员工数量为 " << Employee::getCount() << endl; //显示计数器的值 return 0; }