如何重载[]运算符以支持其他函数中的赋值和const参数?

问题描述

考虑一个类SomeClass

class SomeClass{
    public:
        // Constructors,other members
        float& operator[](const unsigned i);
        friend bool operator==(const SomeClass &A,const SomeClass &B);
};

假设这是此类==运算符的重载方式(不是实际的实现,而是过于简化的版本):

bool operator==(const SomeClass &A,const SomeClass &B){
    if (A[0] == B[0])
        return true;
    return false;
}

这将引发编译器错误,因为重载的[]运算符要求实例非const。但是,如果我更改[]运算符的定义以允许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!

我真的不想在const运算符的参数中删除==,因为操作数在函数内不会改变。处理此问题的正确方法是什么?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)