C++ 重载 [ ] , C++ 模版类的一些事项

MOOC上 很难蒙混过关的CArray3d三维数组模板类:

这道题目大概是希望自己能写一个实现下面这个功能的类;

CArray3D<int> a(3,4,5)

a[i][j][k] = 100;

然后先看一下一些参考资料:

来源:http://en.cppreference.com/w/cpp/language/operators

User-defined classes that provide array-like access that allows both reading and writing typically define two overloads for operator[]: const and non-const variants:

struct T
{
          value_t& operator[](std::size_t idx)       { return mVector[idx]; }
    const value_t& operator[](std::size_t idx) const { return mVector[idx]; }
};

If the value type is known to be a built-in type, the const variant should return by value.

Where direct access to the elements of the container is not wanted or not possible or distinguishing between lvalue c[i] = v; and rvalue = c[i]; usage, operator[] may return a proxy. see for example std::bitset::operator[].

To provide multidimensional array access semantics, e.g. to implement a 3D array access a[i][j][k] = x;, operator[] has to return a reference to a 2D plane, which has to have its own operator[] which returns a reference to a 1D row, which has to have operator[] which returns a reference to the element. To avoid this complexity, some libraries opt for overloading operator() instead, so that 3D access expressions have the Fortran-like syntax a(i, j, k) = x;


那么a[i] = a.operator(i),在类里面有定义,返回的是一个内部类的引用;(这个和比较大小的时候如果定义的 cmp 函数是个类,那么重载的也是cmp(a,b) = cmp.operator(a,b) 这个函数)

a[i][j] = a.operator(i).operator(j), 在类的内部类里面也有定义,返回的是 T*, 比如 int *;

a[i][j][k] = a.operator(i).operator(j).operator(k),在类里面没有定义,此时应该去C++的编译环境里找了,不就是最简单的一维数组么,所以也就找到了- - 。

class CArray3D
{
public:
    class CArray2D{
    private:
        int row;
        int col;
        int size_;
        T *ptr;
    public:
        CArray2D() :row(0), col(0), size_(0){
            ptr = new T[1];
        }
        
        void init(int r, int c){
            row = r; col = c; size_ = r * c;
            delete[] ptr;
            ptr = new T[size_ + 1];
        }
        
        T * operator[](int i){
            return (ptr + i * col); //这里看的出来二维数组应该也是连续的
        }
        
        operator T*(){//only for memset
            return ptr;
        }
    };
    
    CArray2D* a;
    CArray3D(int dimension,int b,int c){
        a = new CArray2D[dimension];
    }
    CArray2D & operator[](int i){//这里比较难,a[i],a[i][j],a[i][j][k]分别返回的是什么呢??
        return a[i];
    }
    
};


猜你喜欢

转载自blog.csdn.net/qq_25175067/article/details/80266003