gpt4 book ai didi

c++ - 错误 : ISO C++ forbids in-class initialization of non-const static member

转载 作者:IT老高 更新时间:2023-10-28 22:23:01 31 4
gpt4 key购买 nike

这是头文件: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 重载构造函数

      lastName(last) 

lastName 重载构造函数

    { //The constructor start
++counter;

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

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

~Employee() {

析构函数 cout << "~Employee() 要求 "<< firstName << ' ' <<姓氏<

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

        --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 <iostream>
#include "employee2.h"
using namespace std;

int main()
{
cout << "Number of employees before instantiation of any objects is "
<< Employee::getCount() << endl;

这里是从类中调用计数器的值

    { 

开始一个新的范围 block

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

结束作用域 block

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

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

最佳答案

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

将头文件中的行改为

static int counter;

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

int Employee::counter = 0;

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

关于c++ - 错误 : ISO C++ forbids in-class initialization of non-const static member,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20310000/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com