const parameter in function prototype

This question already has an answer here:

  • Meaning of “const” last in a C++ method declaration? 7 answers

  • 这是一个const方法,这意味着你可以调用它const对象,也不会改变非mutable成员,也不会调用其他非const方法。

    struct X
    {
        void foo();
        int x;
        void goo() const;
    };
    
    void X::goo() const
    {
       x = 3;  //illegal
       foo();  //illegal
    }
    
    //...
    const X x;
    x.foo();   //illegal
    x.goo();   //OKAY
    

    Basically, it means that method will not modify the state of an instance of that class. This means that it will also not call other members that would change the state of an instance of the class.

    OK:

    class Foo
    {
       int m_foo;
       int GetFoo() const
       {
           return m_foo;
       }
    }
    

    Compile error:

    class Foo
    {
       int m_foo;
       int GetFoo() const
       {
           m_foo += 1;
           return m_foo;
       }
    }
    

    There are deeper considerations, such as performance benefits when passing by reference - if you want to go deeper, the term to search for is 'const correctness'.


    The const in this line means that it is a constant function. This implies that it can't modify the object inside it.

    Thus, if you declare a member function const , you tell the compiler the function can be called for a const object. A member function that is not specifically declared const is treated as one that will modify data members in an object, and the compiler will not allow you to call it for a const object.

    链接地址: http://www.djcxy.com/p/40424.html

    上一篇: C ++调用具有相同签名但范围不同的方法

    下一篇: 函数原型中的const参数