Linker error unresolved external symbol with my cn

2019-08-14 14:15发布

问题:

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.

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

#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;
}

回答1:

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.

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.