何时调用const运算符[],何时调用非const运算符[]?

Ale*_*lex 1 c++ operator-overloading

我有两个非常不同的行为进行读取和写入.在读取的情况下,我想复制一个相当难以提取数据结构的缓冲区.在写入时,我将只写无缓冲结构.

到目前为止,我一直在使用operator []进行访问,所以为了多态,我想继续这样做.

所以我的问题是:当访问时,调用哪个版本?我的想法是const被称为读取,而非const被称为写入.在这种情况下,这是一个简单的实现.否则,它可能会更棘手.

Jer*_*fin 6

要完成您想要的任务,您通常需要operator[]返回代理,并为该代理类型重载operator=operator T(T原始类型).然后,您可以operator T用来处理读取和operator =处理写入.

编辑:代理的基本思想非常简单:返回一个代替原始对象的对象实例.目前,这将具有非常简单的语义(只需在向量中的指定索引处读取和写入char); 在你的情况下,operator=和(特别)内部的逻辑operator T显然会更复杂,但这对基本结构几乎没有影响.

#include <vector>

class X {
    std::vector<char> raw_data;

    class proxy { 
        X &parent;
        int index;   
    public:
        proxy(X &x, int i) : parent(x), index(i) {}

        operator char() const { return parent.raw_data[index]; }

        proxy &operator=(char d) { 
            parent.raw_data[index] = d; 
            return *this;
        }
    };
public:
    X() : raw_data(10) {}
    proxy operator[](int i) { return proxy(*this, i); }
};

#ifdef TEST

#include <iostream>

int main() {
    X x;
    for (int i=0; i<10; i++)
        x[i] = 'A' + i;

    for (int i=0; i<10; i++)
        std::cout << x[i] << "\n";
    return 0;
}
#endif
Run Code Online (Sandbox Code Playgroud)