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

前端 未结 2 1298
太阳男子
太阳男子 2020-12-15 19:54

this is the header file: employee.h

#ifndef EMPLOYEE_H
#define EMPLOYEE_H

#include 
#include 
using namespace std;

class Empl         


        
相关标签:
2条回答
  • 2020-12-15 20:28

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

    Change the line in the header file to

    static int counter;
    

    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.

    0 讨论(0)
  • 2020-12-15 20:33

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

    // 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::size for representing the non-negative employee count and trailing return syntax for functions.

    Accompanying test (ideone link):

    #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;
    }
    
    0 讨论(0)
提交回复
热议问题