#include <iostream>
class test
{
public:
void print()
{
std::cout << _n << std::endl;
}
int& n()
{
returnthis->_n;
}
private:
staticint _n;
};
//int test::_n = 12; // Works fine!
int main()
{
test::_n = 15; // Doesn't work!
test a,b,c;
//a.n() = 10; // Works fine!
a.print();
b.print();
c.print();
return 0;
}
The line 22 is the problem. How can I initialize a static member of a class without instantiating the class first. Line 18 is not what I'm after, not is the line 24. I'd prefer to initialize test::_n in main().
So let me get that strait. staticint _n; in line 19 is not a definition, it is just a declaration, is that correct?
Does that mean that static members of a class are in fact global variables, but their scope has been limited to the class in which they have been defined?