C++ “const” keyword explanation

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

    The difference between the two is that the first has type void(char) and the second has type int()const.

    A function that has such a type with const at the end can only be a member function of a class, and it means that the member function does not change the class value (which this refers to) as seen from outside the class. The compiler will check that to a degree, and any straight write to a class member in a const member function results in a compile time error, and the function can straightly only call const member functions on itself (special directives exist so you can tell the compiler that a member write won't change the class' value as seen from outside. This is done by the mutable keyword).

    In the functions you presented, one had a parameter of type char const. Such a parameter cannot be changed inside its function. It has no effect on the function's type though, and no effect to the callers of the function.

    0 讨论(0)
  • 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;
    
    0 讨论(0)
提交回复
热议问题