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

 liaojiawei 发布于 2023-02-13 16:22

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

问题是什么?我不知道出了什么问题.我一直在思考,但是我没有错.

1 个回答
  • 静态成员的初始化counter不得位于头文件中.

    将头文件中的行更改为

    static int counter;
    

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

    int Employee::counter = 0;
    

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

    2023-02-13 16:26 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有