I am practising the use of static members. I want to have the main file to deal with two headers.
First header:
1 2 3 4 5 6 7 8 9 10 11
#ifndef _FOO_HPP_
#define _FOO_HPP_
class foo{
int _i;
public:
foo(int i): _i(i) {;}
int get_i() {return _i;}
};
#endif
Second header:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#ifndef _BAR_HPP_
#define _BAR_HPP_
#include "foo.hpp"
class bar{
public:
staticint j;
static foo f;
static foo fooval() {j++; return f;} // record how many times fooval has been called and return the static member f
staticint callsfooval() {return j;} // return how many times fooval has been called
};
#endif
/tmp/ccjjQOyJ.o: In function `bar::fooval()':
cp12_38.cpp:(.text._ZN3bar6foovalEv[bar::fooval()]+0x8): undefined reference to `bar::j'
cp12_38.cpp:(.text._ZN3bar6foovalEv[bar::fooval()]+0x11): undefined reference to `bar::j'
cp12_38.cpp:(.text._ZN3bar6foovalEv[bar::fooval()]+0x17): undefined reference to `bar::f'
/tmp/ccjjQOyJ.o: In function `bar::callsfooval()':
cp12_38.cpp:(.text._ZN3bar11callsfoovalEv[bar::callsfooval()]+0x4): undefined reference to `bar::j'
collect2: ld returned 1 exit status
Can anyone tell what these errors mean? How should I revise my codes? Thank you!
static data members are only declared inside the class definition so you have to put the definition in a source file. So to define j you write int bar::j; in a source file. You can also give j another starting value here if you like. int bar::j = 10;
cp12_38.cpp: In function ‘int main()’:
cp12_38.cpp:10: error: invalid use of qualified-name ‘bar::j’
cp12_38.cpp:11: error: invalid use of qualified-name ‘bar::f’
cp12_38.cpp:13: error: ‘f’ was not declared in this scope
I'm still confused. Any comments or hints? Thanks a lot.
Thanks for what you suggested. But it even made the thing worse. I really doubt if these two initialization should appear in class bar (or appear somewhere outside the class but in bar.cpp).