遵循函数/方法签名的 const 是什么意思?

2022-01-23 00:00:00 constants c++

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

According to MSDN: "When following a member function's parameter list, the const keyword specifies that the function does not modify the object for which it is invoked."

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

Could someone clarify this a bit? Does it mean that the function cannot modify any of the object's members?

 bool AnalogClockPlugin::isInitialized() const
 {
     return initialized;
 }

推荐答案

表示该方法不修改成员变量(声明为mutable的成员除外),所以可以调用类的常量实例.

It means that the method do not modify member variables (except for the members declared as mutable), so it can be called on constant instances of the class.

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();
}

相关文章