C ++重载下标运算符的两个版本 [英] c++ two versions of overloading subscript operator

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

问题描述

我的问题是关于以下两者之间的区别:

My question is about the difference between:

const T& operator[](const int nIndex) const;

和:

T& operator[](const int nIndex);

为什么我需要在一个类中同时定义它们,目的是什么?后者就够了吗?

Why would I need both of them defined in a class, what's the purpose? Wouldn't the latter suffice?

推荐答案

成员函数声明的末尾带有const,即使在const对象上也可以调用该函数.这仅对不修改对象状态的成员函数有意义.

A member function declaration with const at the end of it allows that function to be called even on a const object. This only makes sense for member functions that don't modify the state of the object.

比方说,您拥有的使这些运算符重载的类称为X.大概它的行为有点像一个容器,可以通过此operator[]来访问它包含的元素.

Let's say the class you have that overloads these operators is called X. Presumably it behaves a bit like a container, giving access to the elements it contains through this operator[].

现在,假设用户要使用const X:

Now let's say the user wants to use a const X:

const X x = /* fill it */;
use(x[0]);

应该允许用户这样做吗?大概.如果他们想要一个不可变的容器,那么让他们拥有它.如果您未提供operator[]const版本,则他们将无法执行此操作.他们毕竟不是在尝试修改容器,而是在查看其内容.

Should the user be allowed to do this? Probably. If they want a container that is immutable, then let them have it. If you didn't provide the const version of operator[], they wouldn't be able to do this. They're not trying to modify the container after all, they're just looking at its contents.

现在为什么要使operator[]const版本返回const引用?因为它必须.它返回对类本身成员的引用.如果容器是const并返回了非const引用,则调用方将可以使用此运算符来修改其内部信息:

Now why make the const version of operator[] return a const reference? Because it has to. It's returning a reference to a member of the class itself. If the container was const and returned a non-const reference, the caller would be able to modify its internals just by using this operator:

const X x = /* fill it */;
x[0].modify();

哦,亲爱的,我们修改了x的状态,即使它是const.这将是不好的,实际上,编译器甚至不允许您这样做.

Oh dear, we modify the state of x even though it's const. This would be bad and in fact, the compiler won't even let you do it.

这篇关于C ++重载下标运算符的两个版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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