C++ “const” keyword explanation

前端 未结 8 1962
半阙折子戏
半阙折子戏 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:09

    void myfunc(const char x) is very similar to const int x = 5 in your example: It declares a constant locally available within the function myfunc. As it is a constant its value cannot be changed.

    int myfunc() const is a member function of a class. The const indicates that the function would not change the instance of the class the function is executed on. So, within the function, you cannot do something like this->foo = 7 or call other function that are not const.

提交回复
热议问题