c++ - 计数对象实例,在静态变量 C++ 上出现未定义的引用错误
问题描述
我正在尝试使用静态 int 变量来计算员工类对象,但它表示对该变量的未定义引用。这是我的代码
#include<iostream>
using namespace std;
class Employee{
int userID;
string * files;
public:
static int empCount;
Employee(){
userID = ++empCount;
}
~Employee(){
--empCount;
}
Employee(string files[100]){
this->files = files;
}
int getID(){
return this->userID;
}
};
int main(){
Employee a,b,c;
cout << c.getID(); //should print 3
}
我也尝试使用类方法在类外部定义它,但仍然出现错误。这是我在类中声明 setCount 方法后尝试的:
void Employee :: setCount(){
Employee :: empCount = 0;
}
但它仍然给我构造函数、析构函数和 setCount 方法中的未定义引用错误。
这是它给出的错误。
/tmp/ccVBLyUG.o: 在函数Employee::setCount()': main.cpp:(.text+0xa): undefined reference to
Employee::empCount' /tmp/ccVBLyUG.o: 在函数Employee::empCount' main.cpp:(.text._ZN8EmployeeC2Ev[_ZN8EmployeeC5Ev]+0x13): 对Employee::Employee::Employee()': main.cpp:(.text._ZN8EmployeeC2Ev[_ZN8EmployeeC5Ev]+0xa): undefined reference to
的未定义引用Employee::empCount' main.cpp:(.text._ZN8EmployeeC2Ev[_ZN8EmployeeC5Ev]+0x19): undefined reference to
empCount' /tmp/ccVBLyUG.o:在函数Employee::~Employee()': main.cpp:(.text._ZN8EmployeeD2Ev[_ZN8EmployeeD5Ev]+0xa): undefined reference to
Employee::empCount' /tmp/ccVBLyUG.o:main.cpp:(.text._ZN8EmployeeD2Ev[_ZN8EmployeeD5Ev]+0x13) 中:对 `Employee::empCount' 的更多未定义引用collect2:错误:ld 返回 1 个退出状态
解决方案
推荐阅读
- java - 如何从 Scala 访问 Java 类中的公共静态最终成员?
- php - 如何将 WordPress 元框页面属性-> 页面模板下拉菜单转换为单选按钮?
- java - Update() 方法在带有 h2 数据库的 Play Framework 中不起作用
- javascript - D3 将条形图值旋转 90 度
- java - 使用 modelmapper 将列表大小映射到 int 字段
- python - 为数据框编写循环时出现问题
- c# - 从父类的方法中使用子类的静态覆盖属性
- spring - FlatFileItemWriterBuilder-headerCallback() 获取写入的行数
- mailgun - Mailgun 转发到谷歌组停止工作
- python - 选择特定多索引级别的行