常量和非常量运算符重载 [英] Const and Non-Const Operator Overloading

查看:23
本文介绍了常量和非常量运算符重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我很困惑的话题,我需要详细说明.它是一个 const 版本和一个非常量版本的运算符重载.

I have a topic I'm confused on that I need some elaborating on. It's operator overloading with a const version and a non-const version.

// non-const
double &operator[](int idx) {
    if (idx < length && idx >= 0) {
        return data[idx];
    }
    throw BoundsError();
}

我知道这个 lambda 函数接受一个索引并检查其有效性,然后返回类中数组数据的索引.还有一个函数具有相同的主体但函数调用为

I understand that this lambda function, takes an index and checks its validity and then returns the index of the array data in the class. There's also a function with the same body but with the function call as

const double &operator[](int idx) const

为什么我们需要两个版本?

Why do we need two versions?

例如,在下面的示例代码中,下面每个实例中使用的是哪个版本?

For example, on the sample code below, which version is used in each instance below?

Array a(3);
a[0] = 2.0;
a[1] = 3.3;
a[2] = a[0] + a[1];

我假设 const 版本仅在 a[2] 上调用,因为我们不想冒险修改 a[0]a[1].

My hypothesis that the const version is only called on a[2] because we don't want to risk modifying a[0] or a[1].

感谢您的帮助.

推荐答案

当两个版本都可用时,逻辑非常简单:为 const 对象调用 const 版本,为非const 对象调用非const 版本.就是这样.

When both versions are available, the logic is pretty straightforward: const version is called for const objects, non-const version is called for non-const objects. That's all.

在您的代码示例中,a 是一个非 const 对象,这意味着在所有情况下都会调用非 const 版本.const 版本在您的示例中从不调用.

In your code sample a is a non-const object, meaning that the non-const version is called in all cases. The const version is never called in your sample.

拥有两个版本的目的是为非const 对象实现读/写"访问,而为const 对象实现读"访问.对于 const 对象,const 版本的 operator [] 被调用,它返回一个 const double & 引用.您可以通过该 const 引用读取数据,但不能通过它进行写入.

The point of having two versions is to implement "read/write" access for non-const objects and only "read" access for const objects. For const objects const version of operator [] is called, which returns a const double & reference. You can read data through that const reference, but your can't write through it.

这篇关于常量和非常量运算符重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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