错误:ISO C++ 禁止非常量静态成员的类内初始化

2021-12-31 00:00:00 static standards compiler-errors c++ iso

这是头文件:employee.h

this is the header file: 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), 

firstName 重载构造函数

firstName overloaded constructor

      lastName(last) 

lastName 重载构造函数

lastName overloaded constructor

    { //The constructor start
    ++counter; 

它为每个创建的对象加一;

it adds one plus per each object created;

    cout << "Employee constructor for " << firstName
         << ' ' << lastName << " called." << endl;
    }

    ~Employee() { 

析构函数cout<<~Employee() 调用了" <<名字<<' '<<姓氏<<结束;

Destructor cout << "~Employee() called for " << firstName << ' ' << lastName << endl;

返回每个对象的名字和姓氏

Returns the first and last name of each object

        --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; 

这是我出错的地方.但是,为什么?

Here is where i got the error. But, why?

};

主程序:employee2.cpp

principal program: 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; 

这里从类调用计数器的值

Here ir call te counter's value from the class

    { 

开始一个新的范围块

        Employee e1("Susan", "Bkaer"); 

从Employee类初始化e1对象

Initialize the e1 object from Employee class

        Employee e2("Robert", "Jones"); 

从Employee类初始化e2对象

Initialize the e2 object from Employee class

        cout << "Number of employees after objects are instantiated is"
             << Employee::getCount(); 

        cout << "

Employee 1: " << e1.getFirstName() << " " << e1.getLastName()
             << "
Employee 2: " << e2.getFirstName() << " " << e2.getLastName()
             << "

";
    } 

结束作用域块

    cout << "
NUmber of employees after objects are deleted is "
         << Employee::getCount() << endl; //shows the counter's value
} //End of Main

有什么问题?我不知道出了什么问题.我想了很多,但我不知道有什么问题.

What is the problem? I have no idea what's wrong. I have been thinking a lot, but a i do not what is wrong.

推荐答案

静态成员counter的初始化不能在头文件中.

The initialization of the static member counter must not be in the header file.

将头文件中的行改为

static int counter;

并将以下行添加到您的employee.cpp:

And add the following line to your employee.cpp:

int Employee::counter = 0;

原因是将这样的初始化放在头文件中会在包含头文件的每个地方复制初始化代码.

Reason is that putting such an initialization in the header file would duplicate the initialization code in every place where the header is included.

相关文章