链接器错误未解析的外部符号与我的cnt变量 [英] Linker error unresolved external symbol with my cnt variable
问题描述
我有一个与静态变量有关的链接问题.这是我第一次尝试使用静态变量.我正在创建一个向量,并希望cnt变量在所有Student对象上都是静态的.
I'm having a linking issue with a static variable. This is the first time I've tried to use a static variable. I am creating a vector and want the cnt variable to be static accross all Student objects.
我一直在努力寻找答案.我读过其他有此问题的人,他们没有声明静态变量,而是需要专门为静态变量创建一个新对象.
I've searched around trying to figure this out. I've read others having this problem where they weren't declaring the static var and they needed to create a new object specifically for the static variable.
我认为在构造函数中声明并设置了sCnt变量.在类中实现静态成员变量的正确方法是什么?
I thought in constructor the sCnt variable is declared and set. What is the proper way to implement a static member variable in a class?
Student.h
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
Student.cpp
#include "Student.h"
Student::Student()
{
id = 0;
sCnt = 0;
}
Student::Student(string ID)
{
id = atoi(ID.c_str());
sCnt = 0;
}
推荐答案
您只需要定义一次即可.将以下内容添加到cpp文件中:
You need to define it, exactly once. Add the following to the cpp file:
int Student::sCnt = 0; // Note the ' = 0' is optional as statics are
// are zero-initialised.
假定应该计算Student
实例的数量,请不要在Student
构造函数中将其设置为0
,在Student
析构函数中对其进行递增和递减.
Assuming it is supposed to count the number of Student
instances don't set it to 0
in the Student
constructors, increment it and decrement in the Student
destructor.
这篇关于链接器错误未解析的外部符号与我的cnt变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!