简体   繁体   中英

What is the use of const in the given function when the member variables are changed by the function?

class StatDemo
{
   private: static int x;
   int y;
   public: void setx(int a) const { x = a; }
   void sety(int b) const { y = b; }
   int getx() {return x; }
   int gety() {return y; }
} ;

What is the use of const when the member variables are changed by the function??

methods not marked const cannot be called on a const object (or ref or pointer to a const object).

StatDemo sd;
StatDemo const & sdr = sd;
sdr.get(x); // error because getx isn't marked const

However, that means that all the data members accessed from within a method marked const are also const , so you cannot change them (without playing tricks).

That's why your setx won't compile -- x is const within those methods.

What is the use of const when the member variables are changed by the function?

As @songyuanyao correctly mentioned, to cause compile errors.

Yet, it is rather a convention. You may still modify members via const_cast on this , or via marking members mutable .

There's a difference between logical and physical constness, as discussed here .

Why may we still modify non-const static members in const methods?

A non-static method of a class has this as a parameter. const qualifier on a method makes this constant (and triggers a compile error when the convention's violated).

A static member isn't related to this in any way: it is the only one for every object of a class. That's why the constness of a method (ie the constness of this ) has no impact on static members of a class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM