1

我有一个静态变量的链接问题。这是我第一次尝试使用静态变量。我正在创建一个向量,并希望 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;
}
4

1 回答 1

5

您需要定义它,恰好一次。将以下内容添加到 cpp 文件中:

int Student::sCnt = 0; // Note the ' = 0' is optional as statics are
                       // are zero-initialised.

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.

于 2012-05-20T21:08:12.273 回答