Reputation: 43
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?
Upvotes: 0
Views: 128
Reputation:
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;
}
Upvotes: 0
Reputation: 10425
A static
member function of class foo
is not associated with an object of that class (doesn't have the this
pointer).
And how can you access the member variables of foo
without an object? Unless they are static
themselves, you can't.
You must create an instance of foo
first.
In your case:
static int myClass::getX() {
myClass obj;
obj.x = 10;
return obj.x;
}
Upvotes: 2