I searched the Internet and found that some people said that non-static member function can access static member function or data. Then I wrote a program to verify it.
#include <iostream>
class test
{
public:
static int a;
void printa()
{
std::cout<<a;
}
};
int main(int argc, const char * argv[])
{
test m;
m.printa();
return 0;
}
The code generate linker errors!
Undefined symbols for architecture x86_64:
"test::a", referenced from:
test::printa() in main.o
Declaring a variable as static
inside a class is, well, only a declaration.
You need to define the variable as well, which means adding this line in a single compilation unit :
int test::a = 0;
To be more precise : a compilation unit is basically a .cpp file. You should not put that line directly in a header file, otherwise you will get the opposite error : "multiple definition of...".
This will also, as you have guessed, initialize your variable to 0
once your program starts.
If you put this line under your class declaration, it will fix your problem (in this specific situation : remember not to write this in a header file).
That's because you've only declared test::a
, not defined it:
#include <iostream>
class test
{
...
};
int test::a = 1; //Needs a definition!
You have only declared the static
data member. You have not defined it.
YOu need to do something like int test:: a;
to define it.
See this too
Non-static members are allowed to access static data members. The reverse is not allowed because static members do not belong to any object
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With