关于 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 成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:关于 const 成员函数