遵循函数/方法签名的 const 是什么意思? [英] What does const mean following a function/method signature?

查看:15
本文介绍了遵循函数/方法签名的 const 是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这篇关于遵循函数/方法签名的 const 是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆