C++ “const” keyword explanation

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

    The first function example is more-or-less meaningless. More interesting one would be:

    void myfunc( const char *x );
    

    This tells the compiler that the contents of *x won't be modified. That is, within myfunc() you can't do something like:

    strcpy(x, "foo");
    

    The second example, on a C++ member function, means that the contents of the object won't be changed by the call.

    So given:

    class {
      int x;
      void myfunc() const;
    }
    

    someobj.myfunc() is not allowed to modify anything like:

    x = 3;
    

提交回复
热议问题