我有一个静态变量的链接问题。这是我第一次尝试使用静态变量。我正在创建一个向量,并希望 cnt 变量在所有 Student 对象中都是静态的。
我四处寻找试图弄清楚这一点。我读过其他人有这个问题,他们没有声明静态变量,他们需要专门为静态变量创建一个新对象。
我认为在构造函数中声明并设置了 sCnt 变量。在类中实现静态成员变量的正确方法是什么?
学生.h
#pragma once
#include <iostream>
using namespace std;
class Student
{
public:
Student();
Student(string ID);
virtual ~Student(void);
void cntReset();
int getCnt() const;
int getID() const;
bool operator< (const Student& s) const;
bool operator== (const Student& s) const;
protected:
int id;
static int sCnt;
private:
};
学生.cpp
#include "Student.h"
Student::Student()
{
id = 0;
sCnt = 0;
}
Student::Student(string ID)
{
id = atoi(ID.c_str());
sCnt = 0;
}