Why can a static member function only be declared

2020-06-01 05:51发布

问题:

While implementing a class for creating/updating boxes on the screen, I wanted to add a static member function that makes sure no currently visible boxes overlap (taking its information from a static pointer array to all currently visible boxes)

My initial code had the following structure:

class Box
{
public:
    // ...
    static void arrangeOverlappingBoxes();
};

static void Box::arrangeOverlappingBoxes()
{
    // ...
}

I was quite surprised that this generated an error C2724: 'static' should not be used on member functions defined at file scope.

With some trial, google and error, I figured out that my function definition should lose the keyword static, i.e. it should be

void Box::arrangeOverlappingBoxes()
{
    // ...
}

Yet I have no clue what the rationale behind this could be. It appears to be so asymetric and confusing to have a different function header for its declaration in the class definition and its own definition. Is there any reason for this?

回答1:

Your class definition (in the header file) will provide the function with whatever propreties are necessary :

  • static
  • inlined
  • virtual

Considering that every further object will look at your class definition using the .h then it makes sense that these properties to be defined there.

Furthermore, each function from the class will mentain it's property in the derived classes (for example you need to declare the destructor virtual only in your base class, every subsequent inheritance will take the destructor as virtual).

It makes no sense to redeclare these properties in your implementation body .

Having to declare function proprieties in both .h and .cpp files would actually lead to allot of problems. Imagine this scenario : you declare a function as virtual in a .h file, and as static in the .cpp file. What will the compiler make that function ? virtual or static ? (or more likely a compile error , but the compiler error will just urge you to match in your .cpp file the declaration in the header. You cannot overload a function according to "static" or "virtual").