运算符[] C++ Get/Set

Taz*_*ngo 21 c++

我在告诉运算符[]的get和set之间的区别时遇到了麻烦.我需要告诉这些函数调用之间的区别.

cout << data[5];
data[5] = 1;
Run Code Online (Sandbox Code Playgroud)

我用Google搜索了,我找到的答案仍然无济于事.人们建议通过添加const来使方法的签名不同.我做到了,他们仍然都使用相同的方法.

有我使用过的签名:

const T& operator[](unsigned int index) const;
T& operator[](unsigned int index);
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

650*_*502 21

解决方案是使用"代理"对象来延迟实际操作:

#include <vector>
#include <iostream>

template<typename T>
struct MyArray {
    std::vector<T> data;
    MyArray(int size) : data(size) {}

    struct Deref {
        MyArray& a;
        int index;
        Deref(MyArray& a, int index) : a(a), index(index) {}

        operator T() {
            std::cout << "reading\n"; return a.data[index];
        }

        T& operator=(const T& other) {
            std::cout << "writing\n"; return a.data[index] = other;
        }
   };

   Deref operator[](int index) {
       return Deref(*this, index);
   }
};

int main(int argc, const char *argv[]) {
    MyArray<int> foo(3);
    foo[1] = 42;
    std::cout << "Value is " << foo[1] << "\n";
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

简单性const不能使用,因为您可能需要从非const实例读取,这是您必须延迟操作的原因:赋值发生在"访问之后"并且编译器不会告诉您访问权限是否存在以后会被用作转让的目标.

因此,我们的想法是,在访问时,您只需存储已请求的索引,并等待知道是否正在进行读取或写入操作.通过从代理提供隐式转换运算符,T您知道何时发生读取操作,通过向代理提供和赋值操作符,T您可以知道写入何时发生.