Why can static member function definitions not have the keyword 'static'?

后端 未结 4 1197
北海茫月
北海茫月 2021-01-01 15:28

As per this link on the \'static\' keyword in C++ :

The static keyword is only used with the declaration of a static member, inside the class defini

4条回答
  •  失恋的感觉
    2021-01-01 15:45

    The point is, that static has several, very different meanings:

    class Foo {
        static void bar();
    }
    

    Here the static keyword means that the function bar is associated with the class Foo, but it is not called on an instance of Foo. This meaning of static is strongly connected to object orientation. However, the declaration

    static void bar();
    

    means something very different: It means that bar is only visible in file scope, the function cannot be called directly from other compilation units.

    You see, if you say static in the class declaration, it does not make any sense to later restrict the function to file scope. And if you have a static function (with file scope), it does not make sense to publish it as part of a class definition in a public header file. The two meanings are so different, that they practically exclude each other.


    static has even more, distinct meanings:

    void bar() {
        static int hiddenGlobal = 42;
    }
    

    is another meaning, that is similar, but not identical to

    class Foo {
        static int classGlobal = 6*7;
    }
    

    When programming, words don't always the same meaning in all contexts.

提交回复
热议问题