Member function with static linkage

前端 未结 2 950
一个人的身影
一个人的身影 2020-12-08 03:56

I\'m trying to understand why the following is an error:

class Foobar {
 public:
  static void do_something();
};

static void Foobar::do_something() {} // E         


        
相关标签:
2条回答
  • 2020-12-08 04:41

    This question is already well answered. Details for static can be read here

    Golden Rule: The static keyword is only used with the declaration of a static member, inside the class definition, but not with the definition of that static member.

    0 讨论(0)
  • 2020-12-08 04:47

    The keyword static has several different meanings in C++, and the code you've written above uses them in two different ways.

    In the context of member functions, static means "this member function does not have a receiver object. It's basically a normal function that's nested inside of the scope of the class."

    In the context of function declarations, static means "this function is scoped only to this file and can't be called from other places."

    When you implemented the function by writing

    static void Foobar::do_something() {} // Error!
    

    the compiler interpreted the static here to mean "I'm implementing this member function, and I want to make that function local just to this file." That's not allowed in C++ because it causes some confusion: if multiple different files all defined their own implementation of a member function and then declared them static to avoid collisions at linking, calling the same member function from different places would result in different behavior!

    Fortunately, as you noted, there's an easy fix: just delete the static keyword from the definition:

    void Foobar::do_something() {} // Should be good to go!
    

    This is perfectly fine because the compiler already knows that do_something is a static member function, since you told it about that earlier on.

    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题