问题描述
给出如下声明:
class A {
public:
void Foo const;
};
这是什么意思?
Google如果它们可以对const(this)对象进行操作,那么应该使用const关键字声明成员函数。如果函数未声明为const,则不能应用于const对象,并且编译器将给出错误消息。
但我发现有点混乱;可以有更好的条件吗?
感谢。
考虑您的班级的变化 A
。
class A {
public:
void Foo()const;
void Moo();
private:
int m_nState; //如果需要,可以添加mutable关键字
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(); //错误 - 不允许在const对象实例上调用非const函数
A2-> Moo(); // OK
const
函数声明向编译器指示该函数是合同义务不修改 A
的状态。因此,您不能调用 A :: Foo
中的非 - const
函数,也不能更改成员变量的值。 / p>
为了说明, Foo()可能不会调用 A :: SetState
声明非 - const
, A :: GetState
但是是确定,因为它是显式声明 const
。除非使用关键字 mutable
声明,否则不能更改成员 m_nState
。
const
的一个例子是'getter'函数获取成员变量的值。
mutable
关键字指示编译器接受对成员变量的修改,否则会导致编译器错误。它用于当函数需要修改状态,但对象被认为是逻辑一致(常量),无论修改。
Given a declaration like this:
class A {
public:
void Foo() const;
};
What does it mean?
Google turns up this:
But I find that somewhat confusing; can anyone out there put it in better terms?
Thanks.
Consider a variation of your class 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
The const
keyword on a function declaration indicates to the compiler that the function is contractually obligated not to modify the state of A
. Thus you are unable to call non-const
functions within A::Foo
nor change the value of member variables.
To illustrate, Foo() may not invoke A::SetState
as it is declared non-const
, A::GetState
however is ok because it is explicitly declared const
. The member m_nState
may not be changed either unless declared with the keyword mutable
.
One example of this usage of const
is for 'getter' functions to obtain the value of member variables.
The mutable
keyword instructs the compiler to accept modifications to the member variable which would otherwise cause a compiler error. It is used when the function needs to modify state but the object is considered logically consistent (constant) regardless of the modification.
这篇关于当使用C ++中的方法时,const运算符是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!