C++ 常量和非常量运算符重载

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19237411/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:38:41  来源:igfitidea点击:

Const and Non-Const Operator Overloading

c++operator-overloadingconst

提问by James Wilks

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];

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 版本只被调用是a[2]因为我们不想冒险修改a[0]a[1].

Thanks for any help.

谢谢你的帮助。

回答by AnT

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

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

In your code sample ais a non-constobject, meaning that the non-constversion is called in all cases. The constversion is nevercalled in your sample.

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

The point of having two versions is to implement "read/write" access for non-constobjects and only "read" access for constobjects. For constobjects constversion 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。对于const对象constversion ofoperator []被调用,它返回一个const double &引用。您可以通过该常量引用读取数据,但不能通过它写入。

回答by echo

To supply a code example to complement the answer above:

提供一个代码示例来补充上面的答案:

Array a(3);
a[0] = 2.0;  //non-const version called on non-const 'a' object

const Array b(3);
double var = b[1];  //const version called on const 'b' object

const Array c(3);
c[0] = 2.0;  //compile error, cannot modify const object