给出这样的声明:
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
,因为它被声明为非 const
,A: :GetState
但是没问题,因为它被显式声明为 const
。除非使用关键字 mutable
声明,否则成员 m_nState
也不能更改。
const
用法的一个示例是“getter”函数获取成员变量的值。
@1800 Information: I forgot about mutable!
mutable
关键字指示编译器接受对成员变量的修改,否则会导致编译器错误。当函数需要修改状态但无论修改如何,对象都被认为逻辑上一致(常量)时使用它。
关于c++ - const 运算符与 C++ 中的方法一起使用时意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49035/