I have a question about static and static const variable in class.
Especially curious about the memory status about static and static const.
In the following code,
#include <iostream>
using namespace std;
class test{
public:
static const int testConstStatic =1;
static int testStatic;
};
int test::testStatic = 0;
int main(){
cout << test::testStatic << endl;
cout << test::testConstStatic << endl;
return 0;
}
why does 'static int testStatic' need definition to be used and if not, I got 'undefined reference' about testStatic?
Does this definition make linkage about testStatic?
And what about testConstStatic?
Thanks in advance!
UPDATED!!
The main reason of this question was that when I declared static variable as global which surely not defined and printout then no message about 'undefined reference' BUT for the static variable in CLASS without definitino it show the message 'undefined reference'
#include <iostream>
using namespace std;
static int testStaticInGlobal;
class test{
public:
static int testStatic;
};
int test::testStatic = 0;
int main(){
cout << test::testStatic << endl; // 'Undefined reference' error without definition
cout << testStaticInGlobal << endl; // no error without definition
return 0;
}
Thanks!
static const
? Justconst
will sufficestatic const char[]
) that is compared by address against a member to determine whether to dyna-free it while enforcing a never-nullptr policy. Admittedly rare, but it does happen, Outside of that I couldn't agree with you more, especially in what appears to be the OP's case. (though now that I think about i, every example i've seen that does that breaks all the rules by casting the const-away).static int testStaticInGlobal;
is a definition, whilestatic int testStatic;
is not because it's in a class.