C++ “const” keyword explanation

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

    This:

    void myfunc( const char x );
    

    means you you cannot change x inside the function, i.e. this is illegal:

    void myfunc( const char x ) {
        x = ...;
    }
    

    while:

    int myfunc() const;
    

    only makes sense if myfunc() is a method inside a class; it basically means the method cannot modify the class instance (i.e. the state of the instance before and after calling instance.myfunc() will be the same).

提交回复
热议问题