错误:ISO C ++禁止非const静态成员的类初始化 [英] error: ISO C++ forbids in-class initialization of non-const static member
问题描述
这是头文件: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() {
$ b cout<< 〜Employee()调用< firstName<< ''
<< lastName<< endl
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;
这里ir从类
{
开始新范围区块
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 << "\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
有什么问题?
我不知道有什么问题。
我一直在想很多,但是没有什么错误。
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.
推荐答案
/ em>的静态成员计数器
不能在头文件中。
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.
这篇关于错误:ISO C ++禁止非const静态成员的类初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!