C++ “const” keyword explanation

前端 未结 8 1942
半阙折子戏
半阙折子戏 2020-12-24 12:58

When reading tutorials and code written in C++, I often stumble over the const keyword.

I see that it is used like the following:

const          


        
8条回答
  •  天命终不由人
    2020-12-24 13:27

    Before a variable identifier, const indicates that the variable can be initialized and thereafter not modified.

    After a class method name, const indicates that the method will not modify the observable state of the class. The mutable keyword allows internal data to be modified.

    Before a pointer or reference variable, const indicates that the identifier will not be used to modify the referenced data, though it may be changed by other means.

    const int *pInt = &x;
    

    Const can also be used to indicate that the pointer itself cannot be modified:

    int * const pInt = &x;
    

提交回复
热议问题