What is the use of const overloading in C++?(C++ 中 const 重载有什么用?)
问题描述
在 C++ 中,函数的签名部分取决于它是否为 const.这意味着一个类可以有两个具有相同签名的成员函数,除了一个是 const 而另一个不是.如果你有一个这样的类,那么编译器将根据你调用它的对象来决定调用哪个函数:如果它是类的 const 实例,将调用函数的 const 版本;如果对象不是 const,则将调用另一个版本.
In C++, a function's signature depends partly on whether or not it's const. This means that a class can have two member functions with identical signatures except that one is const and the other is not. If you have a class like this, then the compiler will decide which function to call based on the object you call it on: if it's a const instance of the class, the const version of the function will be called; if the object isn't const, the other version will be called.
您希望在什么情况下使用此功能?
In what circumstances might you want to take advantage of this feature?
推荐答案
这只有在成员函数返回一个指针或引用你的类的数据成员(或成员的成员,或成员成员的成员,...等).通常不赞成返回非常量指针或对数据成员的引用,但有时它是合理的,或者只是非常方便(例如 [] 运算符).在这种情况下,您需要提供一个 const 和一个非常量版本的 getter.这样,是否可以修改对象的决定取决于使用它的函数,该函数可以选择将其声明为 const 或 non-const.
This really only makes sense when the member function returns a pointer or a reference to a data member of your class (or a member of a member, or a member of a member of a member, ... etc.). Generally returning non-const pointers or references to data members is frowned upon, but sometimes it is reasonable, or simply very convenient (e.g. [] operator). In such cases, you provide a const and a non-const versions of the getter. This way the decision on whether or not the object can be modified rests with the function using it, which has a choice of declaring it const or non-const.
这篇关于C++ 中 const 重载有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 中 const 重载有什么用?
基础教程推荐
- 一文带你了解C++中的字符替换方法 2023-07-20
- C利用语言实现数据结构之队列 2022-11-22
- C++使用easyX库实现三星环绕效果流程详解 2023-06-26
- 详解c# Emit技术 2023-03-25
- C/C++编程中const的使用详解 2023-03-26
- 如何C++使用模板特化功能 2023-03-05
- C语言 structural body结构体详解用法 2022-12-06
- C++详细实现完整图书管理功能 2023-04-04
- C++中的atoi 函数简介 2023-01-05
- C语言基础全局变量与局部变量教程详解 2022-12-31