Various uses of the const keyword

1. The difference between const modified pointer and variable

const int MAX_AGE = 90;本身
int * const a = new int;//不能改变指针,就是指向不变,但是可以改*a的值
*a = 2;

Note the syntax:

  • Read as pointer to

const (constant) is an adjective

char (variable type) and p (variable name) are of course nouns.

Bjarne gave a mnemonic method in his "The C++ Programming Language"-"".

  1. const char * p is pronounced: p is a pointer to a const char, translated: p is a pointer (variable), which points to a constant character (const char).

  2. char * const p is pronounced: p is a const pointer to a char, translated: p is a constant pointer (const p), which points to a character (variable).

const int MAX_AGE = 90;
int const* a = new int;
const int *a = new int; //两种方式是一样的,不能改变指向的值,但是可以改变指向
*a = 2;
class Entity
{
private:
  const int m_x =3, m_y = 12;
public:
  int Getnum()const
  {
         m_x=1;//是会报错的
    return m_x;
  }
};

When we declare const on the right side of the class method :

Means that our method is read-only and cannot change the value of member variables in the method

class Entity
{
private:
  const int m_x, m_y;
public:
  const int const Getnum()const
  {
    return m_x;
  }
};

const before int: means that the return is of type const int

The const after int: means that this method is promised not to be modified


2.const's wife mutable

class Entity
{
private:
  const int m_x, m_y;
    mutable debug_count = 0;
public:
  int Getnum()const
  {
         debug_count++;
    return m_x;
  }
};

Normally, adding const after the method cannot change the member variable, but when we debug, we need some variables, then we use mutable, then we can change debug_count

Maybe this is the only use of mutable.

 

Guess you like

Origin blog.csdn.net/Matcha_/article/details/113195642