在C ++中使用const重载是什么? [英] What is the use of const overloading in C++?

查看:142
本文介绍了在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和一个非const版本的getter。这样,对象是否可以被修改的决定取决于使用它的函数,它可以选择声明它是const还是非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重载是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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