const函数/方法签名后的含义是什么?

Sco*_*ott 32 c++ const

根据MSDN:"当跟随成员函数的参数列表时,const关键字指定该函数不会修改调用它的对象."

有人可以澄清这一点吗?这是否意味着该函数无法修改任何对象的成员?

 bool AnalogClockPlugin::isInitialized() const
 {
     return initialized;
 }
Run Code Online (Sandbox Code Playgroud)

Pie*_*don 37

这意味着该方法不会修改成员变量(声明为的成员除外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();
}
Run Code Online (Sandbox Code Playgroud)


blw*_*y10 16

还要注意,虽然成员函数不能修改未标记为可变的成员变量,但如果成员变量是指针,则成员函数可能无法修改指针值(即指针指向的地址),但它可以修改指针指向的内容(实际内存区域).

例如:

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;
};
Run Code Online (Sandbox Code Playgroud)