运算符[] C ++获取/设置 [英] Operator[] C++ Get/Set
问题描述
我无法告诉操作员get和set之间的区别[]。我需要说出这些函数调用之间的区别。
I'm having trouble with telling the difference between get and set for the operator[]. I need to tell the difference between these function calls.
cout << data[5];
data[5] = 1;
我用Google搜索了一下,发现的答案仍然无济于事。人们建议通过添加const使方法的签名有所不同。我这样做了,他们仍然都调用了相同的方法。
I googled it, and the answers I found still didn't help. People suggested making the signatures for the methods different by adding const. I did that, and they still both called the same method.
我曾经使用过以下签名:
There are the signatures I had used:
const T& operator[](unsigned int index) const;
T& operator[](unsigned int index);
我在做什么错了?
推荐答案
解决方案是使用代理对象,该对象将延迟实际操作:
The solution is to use a "proxy" object that will delay the actual operation:
#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;
}
简单 const
- ness不能使用,因为您可能需要从非const实例中读取数据,这就是您必须延迟操作的原因:赋值发生在访问之后,并且编译器不会告诉您访问是否是
Simple const
-ness cannot be used because you may need to read from a non-const instance, that is the reason for which you must delay the operation: the assignment happens "after" the access and the compiler doesn't tell you if the access will be later used as a target for assignment or not.
因此,我们的想法是,在访问时,您只存储了已请求的索引,并等待知道是读还是读。正在进行写操作。通过提供从代理到 T
的隐式转换运算符,您可以通过提供和分配从 T到代理的运算符来知道何时发生读取操作。 code>您知道什么时候写。
The idea is therefore that on access you just store away the index that has been requested and wait to know if a reading or a writing operation is happening. By providing an implicit conversion operator from the proxy to T
you know when a reading operation occurs, by providing and assignment operator to the proxy from T
you know when writing occurs.
这篇关于运算符[] C ++获取/设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!