c++ - Member function with static linkage -


i'm trying understand why following error:

class foobar {  public:   static void do_something(); };  static void foobar::do_something() {} // error!  int main() {   foobar::do_something(); } 

this errors "error: cannot declare member function 'static void foobar::do_something()' have static linkage" in g++, , "error: 'static' can specified inside class definition" in clang++.

i understand way fix remove "static" in definition of do_something on line 6. don't, however, understand why issue. mundane reason, such "the c++ grammar dictates so", or more complicated going on?

i think issue here keyword static has several different meanings in c++ , code you've written above uses them in 2 different ways.

in context of member functions, static means "this member function not have receiver object. it's normal function that's nested inside of scope of class."

in context of function declarations, static means "this function scoped file , can't called other places."

when implemented function writing

static void foobar::do_something() {} // error! 

the compiler interpreted static here mean "i'm implementing member function, , want make function local file." that's not allowed in c++ because causes confusion: if multiple different files defined own implementation of member function , declared them static avoid collisions @ linking, calling same member function different places result in different behavior!

fortunately, noted, there's easy fix: delete static keyword definition:

void foobar::do_something() {} // should go! 

this fine because compiler knows do_something static member function, since told earlier on.

hope helps!


Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -