简体   繁体   中英

Access to static member by non-static method

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?

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.

You need to define the static data member (not necessarily initialize it). It will be initialized to 0 automatically. I suppose you're getting a linker error. This is because due to the missing definition, the data member has not been allocated. This has nothing to do with its value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM