函数/方法签名后面的 const 是什么意思?

发布于 2024-08-07 14:10:54 字数 204 浏览 3 评论 0原文

根据 MSDN 的说法:“当遵循成员函数的参数列表时,const 关键字指定该函数不会修改调用它的对象。”

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

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

你列表最软的妹 2024-08-14 14:10:54

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

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

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();
}
软糯酥胸 2024-08-14 14:10:54

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

例如:

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

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 (i.e. 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;
};
时光是把杀猪刀 2024-08-14 14:10:54

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

The compiler won’t allow a const member function to change *this or to
invoke a non-const member function for this object

苍风燃霜 2024-08-14 14:10:54

正如 @delroth 所回答的,这意味着成员函数不会修改任何成员变量,除了声明为可变的变量之外。您可以在此处查看有关 C++ 中 const 正确性的常见问题解答

As answered by @delroth it means that the member function doesn't modify any memeber variable except those declared as mutable. You can see a good FAQ about const correctness in C++ here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文