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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20310000/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:02:41  来源:igfitidea点击:

error: ISO C++ forbids in-class initialization of non-const static member

c++staticcompiler-errorsstandardsiso

提问by mishelashala

this is the header file: employee.h

这是头文件: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) 

Overloaded Constructor

重载构造函数

    : firstName(first), 

firstName overloaded constructor

firstName 重载构造函数

      lastName(last) 

lastName overloaded constructor

lastName 重载构造函数

    { //The constructor start
    ++counter; 

it adds one plus per each object created;

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

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

    ~Employee() { 

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

析构函数 cout << "~Employee() 调用了 " << firstName << ' ' << lastName << endl;

Returns the first and last name of each object

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

        --counter; 

Counter minus one

计数器减一

    }

    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?

这是我遇到错误的地方。但为什么?

};

principal program: employee2.cpp

主程序: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

在这里我从班级中调用 te 计数器的值

    { 

Start a new scope block

开始一个新的范围块

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

Initialize the e1 object from Employee class

从 Employee 类初始化 e1 对象

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

Initialize the e2 object from Employee class

从 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";
    } 

end the scope block

结束范围块

    cout << "\nNUmber 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.

问题是什么?我不知道出了什么问题。我一直在想很多,但我不知道有什么错。

回答by PMF

The initializationof the static member countermust not be in the header file.

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

Change the line in the header file to

将头文件中的行更改为

static int counter;

And add the following line to your employee.cpp:

并将以下行添加到您的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.

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

回答by mucaho

According to a similar SO answerthere is another approach, in particular suited for your current implementation (header-only library):

根据类似的 SO 答案,还有另一种方法,特别适合您当前的实现(仅标头库):

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

I took the liberty to use std::sizefor representing the non-negative employee count and trailing return syntaxfor functions.

我冒昧地std::size用于表示非负员工计数和函数的尾随返回语法

Accompanying test (ideone link):

伴随测试(ideone链接):

#include "Employee.h"

int main() {
    std::cout << "Initial employee count = " << Employee::getCount() << std::endl;
    // printed "count = 0"

    Employee emp1 {};
    std::cout << "Count after an employee created = " << Employee::getCount() << std::endl;
    // printed "count = 1"

    {
        Employee emp2 {};
        std::cout << "Count after another employee created = " << Employee::getCount() << std::endl;
        // printed "count = 2"
    }
    std::cout << "Count after an employee removed = " << Employee::getCount() << std::endl;
    // printed "count = 1"

    return 0;
}