繁体   English   中英

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

[英]How to overload the [] operator to support both assignment and const parameters in other functions?

考虑一个类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 ,因为操作数在函数内不会改变。 处理这个问题的正确方法是什么?

重载operator []以提供两者:

float& operator [](unsigned int i);
float operator [](unsigned int i) const;

对于复制不便宜的通用T ,请使用T const&返回值。 实现读/写operator []的一般模式是

T& operator [](index_type i);
T const& operator [](index_type i) const;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM