在类的函数中使用'const' [英] Using 'const' in class's functions

查看:265
本文介绍了在类的函数中使用'const'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了很多const关键字在函数中的使用,所以我想知道它是什么。我在这里读了smth: 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的真正定义和用法是什么? / p>

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.

这篇关于在类的函数中使用'const'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆