[英]How to overload the [] operator to support both assignment and const parameters in other functions?
Consider a class SomeClass
:考虑一个类
SomeClass
:
class SomeClass{
public:
// Constructors, other members
float& operator[](const unsigned i);
friend bool operator==(const SomeClass &A, const SomeClass &B);
};
Suppose this is how the ==
operator is overloaded for this class (not the actual implementation, but an overly simplified version):假设这是
==
运算符为此类重载的方式(不是实际实现,而是过度简化的版本):
bool operator==(const SomeClass &A, const SomeClass &B){
if (A[0] == B[0])
return true;
return false;
}
This would throw a compiler error, since the overloaded []
operator requires the instance to be non- const
.这将引发编译器错误,因为重载的
[]
运算符要求实例为非const
。 However, if I change the definition of the []
operator to allow for const
instances, I can no longer do assignment:但是,如果我更改
[]
运算符的定义以允许const
实例,则无法再进行赋值:
// ASSUMING: const float& operator[](const unsigned i) const;
SomeClass a;
a[0] = 0; // error, because the return value of [] is a reference to const!
I really don't want to drop the const
in the parameters of the ==
operator, since the operands don't change within the function.我真的不想在
==
运算符的参数中删除const
,因为操作数在函数内不会改变。 What is the right way to deal with this issue?处理这个问题的正确方法是什么?
Overload operator []
to provide both:重载
operator []
以提供两者:
float& operator [](unsigned int i);
float operator [](unsigned int i) const;
For a generic T
that's not cheap to copy, use a T const&
return value.对于复制不便宜的通用
T
,请使用T const&
返回值。 The general pattern for implementing read/write operator []
is实现读/写
operator []
的一般模式是
T& operator [](index_type i);
T const& operator [](index_type i) const;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.