我遇到了静态变量的链接问题。这是我第一次尝试使用静态变量。我正在创建一个向量,并希望cnt变量在所有Student对象中都是静态的。
我试图解决这个问题。我已经读过其他有这个问题的人,他们没有声明静态var,他们需要专门为静态变量创建一个新对象。
我认为在构造函数中声明并设置了sCnt变量。在类中实现静态成员变量的正确方法是什么?
Student.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:
};
Student.cpp
#include "Student.h"
Student::Student()
{
id = 0;
sCnt = 0;
}
Student::Student(string ID)
{
id = atoi(ID.c_str());
sCnt = 0;
}
答案 0 :(得分:5)
您需要定义一次。将以下内容添加到cpp文件中:
int Student::sCnt = 0; // Note the ' = 0' is optional as statics are
// are zero-initialised.
假设它应该计算Student
个实例的数量,不要在0
构造函数中将其设置为Student
,在Student
析构函数中递增它并递减