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

查看:158
本文介绍了Const和非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();
}



我理解这个函数是一个类的一部分,它的逻辑,返回类中数组数据的索引。还有一个具有相同体的函数,但函数调用为

I understand that this function part of a class, takes an index and checks that its logical, 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 version?

这个样例问题也可能有助于阐述。
下面每个实例中使用哪个版本?

This sample question also might help elaborate. 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] / code>因为我们不想冒险修改 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 object,这意味着在所有情况下都调用非< - code> 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 对象 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.

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

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