在类的函数中使用“const"
我在类中看到了很多将 const 关键字放在函数后面的用法,所以我想知道它是关于什么的.我在这里读到了: http://duramecho.com/ComputerInformation/WhyHowCppConst.html .
I've seen a lot of uses of the const keyword put after functions in classes, so i wanted to know what was it about. I read up smth at here: http://duramecho.com/ComputerInformation/WhyHowCppConst.html .
它说使用 const 是因为函数可以尝试更改对象中的任何成员变量".如果这是真的,那么它应该在任何地方使用,因为我不希望以任何方式更改或更改任何成员变量.
It says that const is used because the function "can attempt to alter any member variables in the object" . If this is true, then should it be used everywhere, because i don't want ANY of the member variables to be altered or changed in any way.
class Class2
{ void Method1() const;
int MemberVariable1;}
那么, const 的真正定义和用途是什么?
So, what is the real definition and use of const ?
推荐答案
可以在 const 对象上调用 const 方法:
A const method can be called on a const object:
class CL2
{
public:
void const_method() const;
void method();
private:
int x;
};
const CL2 co;
CL2 o;
co.const_method(); // legal
co.method(); // illegal, can't call regular method on const object
o.const_method(); // legal, can call const method on a regulard object
o.method(); // legal
此外,它还告诉编译器 const 方法不应该改变对象的状态,并且会捕捉到这些问题:
Furthermore, it also tells the compiler that the const method should not be changing the state of the object and will catch those problems:
void CL2::const_method() const
{
x = 3; // illegal, can't modify a member in a const object
}
使用 mutable 修饰符对上述规则有一个例外,但在您涉足该领域之前,您应该首先熟悉 const 的正确性.
There is an exception to the above rule by using the mutable modifier, but you should first get good at const correctness before you venture into that territory.
相关文章