-1

I wish to access a static variable declared in a class. Following this post's suggestions, I defined two files,

in test.h:

class foo
{
    private:
        static int i;
};

in test.cpp:

#include "test.h"
int main(int argc, char* argv[]){

    int foo::i = 0;
}

But, the compiler still generates this error when I do make test. I'm using a mac:

test.cpp:16:11: error: definition or redeclaration of 'i' not allowed inside a function
    int foo::i = 0;

How can I fix it?

Community
  • 1
  • 1
Pippi
  • 2,451
  • 8
  • 39
  • 59
  • 2
    It is private member which means other functions including main() cant access it. you need to write `int foo::i=0` in global scope – youssef Apr 30 '15 at 20:03
  • The answers in that post declared the variable as private, so I assumed it is correct. It also makes sense to me that the variable should be public. – Pippi Apr 30 '15 at 20:05
  • you don't need to make it public , you can write a `static` public member function which access the value and change it in `main()` – youssef Apr 30 '15 at 20:08
  • if `static int i;` is important for `foo ` class mechanism of work so better not to expose it to public but change it by static function. – youssef Apr 30 '15 at 20:12

3 Answers3

4
  1. int foo::i = 0; belongs at global scope, not in main

  2. Because it is private, main will not be able to access it. You'll have to make the access specifier less restrictive (i.e. public) or make an accessor function for it.

Dark Falcon
  • 43,592
  • 5
  • 83
  • 98
3

... The definition for a static data member shall appear in a namespace scope enclosing the member’s class definition. ...

(C++14 standard, [class.static.data]/1).

You cannot define a static member at block scope, as you have attempted to do.

If you want main to have access to the private member, write a public accessor function. Or make main a friend (probably a worse idea).

Brian Bi
  • 111,498
  • 10
  • 176
  • 312
0

To add to the other answers here:

Constant static members can be initialized inside the class definition if they are of integral or enumerated type:

struct X {
const static int n = 1;
const static int m{2}; // since C++11
};
Andreas DM
  • 10,685
  • 6
  • 35
  • 62