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

后端 未结 4 1177
北海茫月
北海茫月 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:40

    You have to understand the difference between declaration and implementation, and that will answer your question:

    Declaration: Is how C++ functions and methods are seen before compiling the program. It's put in a header file (.h file).

    Implementation: Is how the compiler links a declaration to a real task in binary code. The implementation can be compiled on the fly (from source files, .cpp or .cxx or .cc), or can be already compiled (from shared libraries or object files).

    Now going back to your question, when you declare something as static, it's something not related to the implementation, but related to how the compiler sees the decleration while compiling the code. For example, if you label functions in source files "static", then that's meaningless, because that information cannot be carried to compiled objects and shared libraries. Why allow it? On the contrary, it could only cause ambiguity.

    For the exact same reason, default parameters must go into the header, not the source files. Because source files (that contain implementations), cannot carry the default parameter information to a compiled object.

提交回复
热议问题