According to the C ++ standard (9.2.3.2 static data elements)
1 Static data member is not part of class subobjects ...
And (9.2.2.1 This pointer)
1 In the body of a non-static (9.2.1) member function, the keyword is the prvalue expression whose value is the address of the object for which the function is called. The type of this member in a function of class X is X *. If a const member function is declared, the type of it is const X * , ...
Finally (9.2.2 Non-Static Member Functions)
3 ... if the name search (3.4) resolves the name in the id expression to a non-static non-type member of some class C, and if either the id expression is potentially evaluated or C is X or the base class X, the id expression is converted to an access expression class member (5.2.5), using (* this) (9.2.2.1) as the postfix expression to the left of. Operator.
So in this class definition
class A { public: static int a; void set() const { a = 10; } };
the static data member a not a subobject of an object of class type, and the this pointer is not used to access the static data element. Thus, any member function, a non-static constant or not a constant, or a static member function can modify a data item because it is not a constant.
In this class definition
class A { public: int a; void set() const { a = 10; } };
the non-static data member a is a subobject of an object of type class. To access it in a member function, either the syntax for accessing membership in this syntax is used. You cannot use the this constant pointer to change a data item. And the pointer really has type const A * inside the set function, because the function is declared using the const qualifier. If the function did not have a qualifier, in this case the data item could be changed.
Vlad from Moscow May 12 '17 at 11:51 2017-05-12 11:51
source share