I am following simple examples to build up my understanding on private static members. However, I am getting compilation errors.
Here is the example, I am following -
https://www.ibm.com/support/knowledgecenter/en/SSLTBW_2.1.0/com.ibm.zos.v2r1.cbclx01/cplr038.htm
have changed the c++ version to see if it something to do with c++ version.
class test1
{
static int i;
static int j;
static int k;
static int f() { return 0;}
int p;
public:
test1()
{
p = 0;
}
};
int main(void)
{
test1 t;
int test1::i = test1::f();
int test1::j = test1::i;
return 0;
}
Compiling this code -
Why does it fail here whereas the example link says it works.
$g++ -std=c++14 t1.cpp -o t1.out
t1.cpp: In function ‘int main()’:
t1.cpp:19:16: error: qualified-id in declaration before ‘=’ token
int test1::i = test1::f();
^
t1.cpp:20:16: error: qualified-id in declaration before ‘=’ token
int test1::j = test1::i;
It works if I do like this -
class test1
{
static int i;
static int j;
static int k;
static int f() { return 0;}
int p;
public:
test1()
{
p = 0;
}
};
int test1::i = test1::f();
int test1::j = test1::i;
int main(void)
{
test1 t;
return 0;
}
Why it has to be defined outside of main() ? It works with private also. However, it cannot be defined inside main function. My understanding is that static int inside class is just a declaration. It needs to be defined somewhere. I am defining it within main() but it doesn't work. It needs to be global and I don't know why it needs to be global? It has nothing to do with private/public in my opinion. Please clarify my doubt here.
JavaScript questions and answers, JavaScript questions pdf, JavaScript question bank, JavaScript questions and answers pdf, mcq on JavaScript pdf, JavaScript questions and solutions, JavaScript mcq Test , Interview JavaScript questions, JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)