about const member function(关于 const 成员函数)
问题描述
我遇到了两个关于const成员函数的解释
I met two explanation of const member function
class A{
public:
...
void f() const {}
...
}
- 这意味着它只能访问常量成员;
- 表示不修改任何成员;
我认为第二个是正确的.但是为什么第一个出来?有什么需要澄清的吗?
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 成员函数
基础教程推荐
- 一文带你了解C++中的字符替换方法 2023-07-20
- C利用语言实现数据结构之队列 2022-11-22
- C++详细实现完整图书管理功能 2023-04-04
- C++中的atoi 函数简介 2023-01-05
- C语言 structural body结构体详解用法 2022-12-06
- C语言基础全局变量与局部变量教程详解 2022-12-31
- 详解c# Emit技术 2023-03-25
- 如何C++使用模板特化功能 2023-03-05
- C++使用easyX库实现三星环绕效果流程详解 2023-06-26
- C/C++编程中const的使用详解 2023-03-26