c++ - const 运算符与 C++ 中的方法一起使用时意味着什么?

标签 c++

给出这样的声明:

class A {
public:
    void Foo() const;
};

这是什么意思?

Google 发现了这个:

Member functions should be declared with the const keyword after them if they can operate on a const (this) object. If the function is not declared const, in can not be applied to a const object, and the compiler will give an error message.

但我觉得这有点令人困惑;谁能用更好的术语表达出来?

谢谢。

最佳答案

考虑类 A 的变体。

class A {
public:
    void Foo() const;
    void Moo();

private:
    int m_nState; // Could add mutable keyword if desired
    int GetState() const   { return m_nState; }
    void SetState(int val) { m_nState = val; }
};

const A *A1 = new A();
A *A2 = new A();

A1->Foo(); // OK
A2->Foo(); // OK

A1->Moo(); // Error - Not allowed to call non-const function on const object instance
A2->Moo(); // OK

函数声明中的const 关键字向编译器表明该函数在契约(Contract)上有义务不修改A 的状态。因此,您无法在 A::Foo 中调用非 const 函数,也无法更改成员变量的值。

为了说明,Foo() 可能不会调用 A::SetState,因为它被声明为非 constA: :GetState 但是没问题,因为它被显式声明为 const。除非使用关键字 mutable 声明,否则成员 m_nState 也不能更改。

const 用法的一个示例是“getter”函数获取成员变量的值。

@1800 Information: I forgot about mutable!

mutable 关键字指示编译器接受对成员变量的修改,否则会导致编译器错误。当函数需要修改状态但无论修改如何,对象都被认为逻辑上一致(常量)时使用它。

关于c++ - const 运算符与 C++ 中的方法一起使用时意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49035/

相关文章:

C++、Visual Studio 2012、LIB、DLL、包含、源代码和链接器

c++ - AND 表现得像 OR?

c++ - Firebird 数据库文件拷贝打不开

c++ - 如何在 ncurses 中启用 32k 颜色对?

c++ - vector::insert 在 VS2010 中执行意外结果

c++ - 为什么将对象引用参数传递给线程函数无法编译?

c++ - 我对递归函数中变量如何工作的理解是否正确?

c++ - Qt:在QMap中找到最接近的QVector3D

c++ - 在 C++ 中读取 CSV 文件中的两列

c++ - 在定义一个充满成员的结构时,是否为该结构类型的每个变量创建了这些成员?