Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access to static member by non-static method

Tags:

c++

This must be very trivial, but I can't find it out:

struct Test {
  static int n;
  void Save(int val) {
    Test::n = val;
  }
};

int main() {
  Test t;
  t.Save(2);
  return 0;
}

Why there is undefined reference to Test::n at line 4?

like image 247
Jan Turoň Avatar asked Oct 17 '25 19:10

Jan Turoň


1 Answers

You need to define the static:

struct Test {
  static int n;
  void Save(int val) {
    Test::n = val;
  }
};

int Test::n = 0;

Note that the definition must appear in an implementation file, not a header, otherwise you'll get a multiple definition error.

like image 133
Luchian Grigore Avatar answered Oct 19 '25 09:10

Luchian Grigore