在类的函数中使用“const"

Using #39;const#39; in class#39;s functions(在类的函数中使用“const)
本文介绍了在类的函数中使用“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.

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)