'static' for c++ class member functions?
Why is the static keyword necessary at all?
Why c开发者_开发问答an't the compiler infer whether it's 'static' or not?
As follows:
Can I compile this function without access to non-static member data? Yes -> static funcion. No -> non-static function.
Is there any reason this isn't inferred?
If you expect the compiler to decide on the spot whether it's static or not, how does that affect external source files linking against the header file that just defines the method signatures?
The propery of being static or non-static affects the function type. Non-static member functions have an implicit this
parameter, while static ones don't, for one example.
In other words, there's a major qualitative difference between static and non-static member functions. The compiler cannot "infer" this. This is a matter of the author's intent.
If I want (and need) my function to be non-static, I make it non-static, even if it doesn't access any non-static members of the class. If the compiler suddently decides to make my non-static function static just because it doesn't access any non-static members of the class, in general case it will destroy the functionality of the code.
Yes the compiler could, but it has no knowledge of your intent. And the original designers probably thought that supplying your intent was important.
Having redundancy in like this in the language helps to insure that many programmer errors will end up being caught by the compiler.
Another reason: If the function is static, it can't be overridden in derived classes. No polymorphism.
精彩评论