具有const和不具有const的相同功能-什么时候以及为什么? [英] Same function with const and without - When and why?

查看:88
本文介绍了具有const和不具有const的相同功能-什么时候以及为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  T& f(){//一些代码...} 
const T& f()const {//一些代码...}

我已经看到了几个现在(在我一直在研究的入门书中)。我知道第一个const使返回值const,换句话说:不可修改。我相信,第二个const允许也可以为const声明的变量调用该函数。



但是,为什么要在同一个类定义中同时使用两个函数呢?编译器如何区分这些?我相信第二个f()(带有const)也可以用于非const变量。

解决方案


但是为什么要在一个类定义中同时具有相同的类定义?


同时拥有两个功能可以使您: / p>


  • 在可变对象上调用该函数,并根据需要修改结果;和

  • 调用 const 对象上的函数,仅查看结果。



只有第一个,您不能在 const 对象上调用它。仅使用第二个,您就无法使用它来修改它返回引用的对象。


以及编译器如何区分这些?


在调用函数时选择 const 重载 const 对象(或通过引用或指向 const 的指针)。


我相信第二个f()(带有const)可以用于非const变量,如下所示:


如果那是唯一的重载,那就可以。在两个重载的情况下,都将选择非 const 重载。


T& f() { // some code ... }
const T& f() const { // some code ... }

I've seen this a couple of times now (in the introductory book I've been studying thus far). I know that the first const makes the return value const, in other words: unmodifiable. The second const allows that the function can be called for const declared variables as well, I believe.

But why would you have both functions in one and the same class definition? And how does the compiler distinguish between these? I believe that the second f() (with const) can be called for non-const variables as well.

解决方案

But why would you have both functions in one and the same class definition?

Having both allows you to:

  • call the function on a mutable object, and modify the result if you like; and
  • call the function on a const object, and only look at the result.

With only the first, you couldn't call it on a const object. With only the second, you couldn't use it to modify the object it returns a reference to.

And how does the compiler distinguish between these?

It chooses the const overload when the function is called on a const object (or via a reference or pointer to const). It chooses the other overload otherwise.

I believe that the second f() (with const) can be called for non-const variables as well.

If that were the only overload, then it could. With both overloads, the non-const overload would be selected instead.

这篇关于具有const和不具有const的相同功能-什么时候以及为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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