【问题标题】:What does const mean following a function/method signature? [duplicate]遵循函数/方法签名的 const 是什么意思? [复制]
【发布时间】:2010-12-05 17:05:40
【问题描述】:

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

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

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

【问题讨论】:

标签: c++ constants


【解决方案1】:

表示该方法不修改成员变量(声明为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();
}

【讨论】:

  • 您需要阅读有关 C++ const-ness 的信息。您需要在 const STL 对象等上使用 const_iterator's。
  • 确实,const-正确性对于理解和实践非常重要。
  • 另外,const 方法只能调用 static 或其他 const 方法。
  • 小修正:方法承诺不改变对象。 (有一些句法结构可以让你绕过这个承诺。当然,使用它们通常是很恶心的——但它们就在那里,这是有原因的。)
  • 为什么第一次调用失败?
【解决方案2】:

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

例如:

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-pointer-to-int、pointer-to-const-int 和 const-pointer-to-const-int 之间的区别。 const 方法使指针变为 const。
  • 您的意思可能是“...成员变量标记为可变...”。
  • 哎呀,哈哈。对此感到抱歉。
  • 如果我想定义一个不修改成员值并且成员值指向的方法,我应该做void member() const const*吗?
【解决方案3】:

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

【讨论】:

    【解决方案4】:

    正如@delroth 所回答的,这意味着成员函数不会修改任何成员变量,除了那些声明为可变的变量。你可以看到关于 C++ 中 const 正确性的一个很好的常见问题解答here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-07
      • 1970-01-01
      • 2011-10-05
      • 2011-05-02
      • 2011-03-09
      • 2018-07-31
      • 1970-01-01
      • 2015-02-01
      相关资源
      最近更新 更多