What does const mean following a function/method signature?

This question already has an answer here:

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

  • 这意味着该方法不会修改成员变量(除了声明为mutable的成员),所以它可以在类的常量实例上调用。

    class A
    {
    public:
        int foo() { return 42; }
        int bar() const { return 42; }
    };
    
    void test(const A& a)
    {
        // Will fail
        a.foo();
    
        // Will work
        a.bar();
    }
    

    Note also, that while the member function cannot modify member variables not marked as mutable, if the member variables are pointers, the member function may not be able to modify the pointer value (ie the address to which the pointer points to), but it can modify what the pointer points to (the actual memory region).

    So for example:

    class C
    {
    public:
        void member() const
        {
            p = 0; // This is not allowed; you are modifying the member variable
    
            // This is allowed; the member variable is still the same, but what it points to is different (and can be changed)
            *p = 0;
        }
    
    private:
        int *p;
    };
    

    编译器不允许const成员函数更改* this或为此对象调用非const成员函数

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

    上一篇: 函数名称后不久的const类型限定符

    下一篇: const在函数/方法签名后的含义是什么?