关于const成员函数 [英] about const member function

查看:125
本文介绍了关于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对你自己的引用来破坏类的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 ++常见问题涵盖的范围非常广泛。

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:

  • Const-correctness (cprogramming.com)
  • Const correctness (C++ FAQ Lite)

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

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