两个数组下标超载读写 [英] Two array subscript overloading to read and write

查看:100
本文介绍了两个数组下标超载读写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想有两个数组下标运算符重载类:一个用于读取,而另一个用于写

I'd like to have a class with two array subscript operator overloads: one used for reading and the other for writing.

该pourpose是保持变化的计数器。我读(在 http://faculty.cs.niu.edu/ 〜麦克马​​洪/ CS241 / c241man / node97.html ),我可以做这样的事情:

The pourpose is to keep a counter of changes. I read (at http://faculty.cs.niu.edu/~mcmahon/CS241/c241man/node97.html) that I could do something like this:

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;
};

但是,这并不在我的情况下工作。我使用的是G ++ 4.7与-std = C ++ 11和实际上只有正在写被印在屏幕上,即使我做的:

But that doesn't work in my case. I'm using g++ 4.7 with -std=c++11 and actually only "Is writing" is printed on screen, even if I do:

Array<int> a;
a[0] = 3;
cout << a[0] << endl;

我还注意到,后者从来没有通过检查与gcov的源调用。
该网页上的方法完全错误的,或者是我很misinter preting?

I also noticed that the latter is never called by inspecting the source with gcov. Is the method on that page completely wrong, or is something I'm misinterpreting?

先谢谢了。

推荐答案

这只是一个粗略的想法,我还没有想过各方面的影响,但与过载分配和转换操作符的代理类可以解决你的问题:

This is only a rough idea and I haven't thought about all the implications, but a proxy class with overloaded assignment and cast operators could solve your problem:

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&放大器更好;得到(INT指数)常量T&安培;得到(INT指数)常量无效认沽(INT指数,常量T&安培;值)。

On the other hand, you probably would be better off by implementing separate functions for reading and writing elements of your array, such as T& get(int index), const T& get(int index) const and void put(int index, const T& value).

这篇关于两个数组下标超载读写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆