关于 const 成员函数

about const member function(关于 const 成员函数)
本文介绍了关于 const 成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了两个关于const成员函数的解释

I met two explanation of const member function

class A{
  public:
  ...
  void f() const {}
  ...
}

  1. 这意味着它只能访问常量成员;
  2. 表示不修改任何成员;

我认为第二个是正确的.但是为什么第一个出来?有什么需要澄清的吗?

I think the second one is right. But why does the first one come out? Is there anything to be clarify?

谢谢!

推荐答案

你可以在一个 const 成员函数中检查所有的类成员值,在某些情况下你甚至可以改变成员变量的值.第一个解释是不正确的,我不知道它来自哪里.第二种解释是正确的,但有一些例外.

You can examine all class member values in a const member function, and in some cases you can even change the value of member variables. The first explanation is incorrect, I don't know where it comes from. The second explanation is correct, but with a few exceptions.

这条规则有一些例外.您还可以在 const 成员函数中更改可变变量,例如像这样声明的成员变量:

There are some exceptions to this rule. You can also change mutable variables in a const member function, for example a member variable declared like this:

mutable float my_rank;

您还可以通过 const_cast'ing 对自己的引用来破坏类中的 const 正确性,如下所示:

You can also break const-correctness in a class by const_cast'ing a reference to yourself like this:

Class* self = const_cast<Class*> (this);

虽然在 C++ 中技术上允许,但这通常被认为是糟糕的形式,因为它丢弃了设计中的所有 const 修饰符.除非您确实必须这样做,否则不要这样做,并且如果您发现自己必须这样做很多,这表明您的设计存在问题.C++ FAQ 很好地涵盖了这一点.

While technically allowed in C++, this is usually considered poor form because it throws away all of the const modifiers of your design. Don't do this unless you actually have to, and if you find yourself having to do this quite a lot that suggests a problem with your design. The C++ FAQ covers this very well.

如果您想进一步阅读,这里有两个参考资料:

Here are two references in case you want to do more reading:

  • 常量正确性 (cprogramming.com)
  • 常量正确性(C++ FAQ Lite)

这篇关于关于 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?(易失性成员变量与易失性对象?)