我想要一个带有两个数组下标运算符重载的类:一个用于读取,另一个用于写入。
pourpose是为了防止变化。我读(在http://faculty.cs.niu.edu/~mcmahon/CS241/c241man/node97.html)我可以做这样的事情:
template<typename T>
class Array
{
public:
Array()
{
data = new T[100];
}
T &operator[] (int index)
{
cout << "Is writing\n";
changes++;
return data[index];
}
T operator[] (int index) const
{
cout << "Is reading\n";
return data[index];
}
private:
T *data;
int changes;
};
但这在我的情况下不起作用。我正在使用带有-std = c ++ 11的g ++ 4.7,实际上只有“正在写”才会打印在屏幕上,即使我这样做了:
Array<int> a;
a[0] = 3;
cout << a[0] << endl;
我还注意到,后者永远不会通过gcov检查源来调用。 该页面上的方法是完全错误的,还是我误解了?
提前致谢。
答案 0 :(得分:4)
const
为this
时才会调用 const
重载。它不是确定它是“读”还是“写”操作。
答案 1 :(得分:1)
这只是一个粗略的想法,我没有想到所有的含义,但是具有重载赋值和转换运算符的代理类可以解决您的问题:
template<typename T>
class CountingProxy
{
public:
CountingProxy(int& counter, T& ref) : counter_(counter), ref_(ref)
{
}
CountingProxy<T>& operator=(const T& o)
{
cout << "Is writing\n";
counter_++;
ref_ = o;
return *this;
}
operator T()
{
cout << "Is reading\n";
return ref_;
}
private:
int& counter_;
T& ref_;
};
template<typename T>
class Array
{
public:
Array()
{
data = new T[100];
}
CountingProxy<T> operator[] (int index)
{
return CountingProxy<T>(changes, data[index]);
}
T operator[] (int index) const
{
cout << "Is reading\n";
return data[index];
}
private:
T *data;
int changes;
};
另一方面,通过实现用于读取和编写数组元素的单独函数(例如T& get(int index)
,const T& get(int index) const
和void put(int index, const T& value)
)可能会更好。