sladet sladet - 1 month ago 6
C++ Question

VC++ Classes. Static variables error unresolved external symbol

I have this error that keeps haunting me in all of my programs that is probably just me overlooking something.

code snippet where this error appears:

class myClass {
private:
int x;
public:
static int getX() {
x = 10;
return x;
}
};

int main() {
cout << myClass::getX() << endl;
return 0;
}


The error I am getting says :


error unresolved external symbol


What is causeing this or what is wrong with my code?

Answer

Inside a class you are trying to access the non-static variable using the static method which will not work. You can turn the private member variable x into static and initialize it outside the class. Then your example can look like:

#include <iostream>
class myClass {
private:
    static int x;
public:
    static int getX()
    {
        x = 10;
        return x;
    }
};
int myClass::x = 0;

int main() {
    std::cout << myClass::getX() << std::endl;
    return 0;
}