Why there is no concept of “const-correctness” for class's static member functions?

后端 未结 6 753
别那么骄傲
别那么骄傲 2020-12-19 01:13

Use case:

class A {
  static int s_common;
public:
  static int getCommon () const { s_common; };
};

Typically this results in an error as:

6条回答
  •  萌比男神i
    2020-12-19 01:50

    However had it been allowed, the static member function's "const"ness could have been easily related to the static data members.

    This is where your question becomes confused. A non-static member function declared as const still has non-const access to static data members. The const only applies to this (ie: the non-static data members).

    It would make no sense for a static member function to use const in the same way syntactically, yet have a completely different outcome (ie: making access to static data members const).

    Furthermore, static data members are nothing more than class-scoped global variables that have class access controls (public/private/etc) on them. So it doesn't make sense for some functions to have different const access to them, especially based on their signature.

提交回复
热议问题