首页 > 解决方案 > 计数对象实例,在静态变量 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 个退出状态

标签: c++undefined-referencestatic-variables

解决方案


推荐阅读