C ++ 98 features introduced --mutable common keywords

Before speaking mutable, will speak about const function, before speaking const function, will speak about the difference between the front and rear plus const function

First, the difference between before and after C ++ functions plus the const

  1) was added before the function const: before normal function or static member functions can be const qualifier, the return value of a function representing const, can not be modified (mostly pointer variable for the class), the format

    const RetunType FuncitonName(param list)

  2) after the function plus const: non-static member function can be added const modification, function as a read-only member functions, member variables are read-only.

    ReturnType FunctionName(param list) const

  NOTE: C ++ compiler when const member functions implemented in order to ensure the function can not modify the state of the instance of the class, adds an implicit function in the this parameter const,

    The value of such class member variables, member variables that is read only.

Two, mutable keyword

  mutable (variable) is not commonly used C ++ in a keyword. And only non-static const data members for the class. Since the state of an object is determined by the non-static data members of the object,

  So with the change of data members, state of the object will also change. If a class member function is declared as const type, indicates that the function does not change the state of the object, that is, the

  Function does not modify the non-static data members of the class. But there are times when the need for the assignment of the data members of the class in the class function, this time you need to use the mutable keyword, such as:

  #include <iostream>

  using namespace std;

  class Student

  {

  public:

    Student() {}

    int setAge (int age) const {this-> age = age;} // Error: int front mutable keyword age plus modifiers can compile i.e.

         int SetAge(int age)  {this->age = age;}

      int getAge() const   {return this->age;}

      int GetAge()  {return this->age;}

  private:

    int age;

  }

  

  int main ()

  {

    const Student s1; // const objects

    int age = s1.getAge (); // error: const member functions can only be called after const object

 

    Student s2; // non-const object

    age = s2.getAge (); // call const member functions correctly 

    age = s2.GetAge (); // call the non-const member functions correctly

    

    return 0;

  }

Third, the summary

  1, the const member functions may be altered mutable class member variable.

  2, const object can only be invoked after const member functions.

  3, non-const object can either call const member functions, and can call the non-const member functions.

 

Guess you like

Origin www.cnblogs.com/zhangnianyong/p/11910883.html