C++ 中 const 重载有什么用?

What is the use of const overloading in C++?(C++ 中 const 重载有什么用?)
本文介绍了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 重载有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

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