如何为表示动态分配的二维数组的类重载 [][] 运算符

Yod*_*oda 4 c++ operator-overloading

可能重复:
运算符 [][] 重载

我创建了一个类,其中包含一个包含(在一行中)来自给定二维数组的所有数字的数组。例如给定:类对象中{{1,2}{3,4}}b字段T包含{1,2,3,4}. 我想为这个类重载 [][] 运算符,这样它就会像那样工作

T* t.....new etc.
int val = (*t)[i][j]; //I get t->b[i*j + j] b is an 1dimension array
Run Code Online (Sandbox Code Playgroud)
    class T{
    public:
        int* b;
        int m, n;
        T(int** a, int m, int n){
            b = new int[m*n];
            this->m = m;
            this->n = n;
            int counter = 0;
            for(int i  = 0; i < m; i++){
                for(int j = 0; j < n; j++){
                    b[counter] = a[i][j];
                    counter++;
                }
            }
        }
int main()
{
    int m = 3, n = 5, c = 0;
    int** tab = new int*[m];
    for(int i = 0; i < m; i++)
           tab[i] = new int[n];
    for(int i  = 0; i < m; i++){
        for(int j = 0; j < n; j++){
            tab[i][j] = c;
            c++;
            cout<<tab[i][j]<<"\t";
        }
        cout<<"\n";
    }


    T* t = new T(tab,3,5);

    };
Run Code Online (Sandbox Code Playgroud)

rod*_*igo 5

你不能。您必须重载operator[]以返回代理对象,然后重载operator[]以返回最终值。

就像是:

class TRow
{
public:
    TRow(T &t, int r)
    :m_t(t), m_r(r)
    {}
    int operator[](int c)
    {
        return m_t.tab[m_t.n*m_r + c];
    }
private:
    T &m_t;
    int m_r;
};

class T
{
    friend class TRow;
    /*...*/
public:
    TRow operator[](int r)
    {
         return TRow(*this, r);
    }
};
Run Code Online (Sandbox Code Playgroud)

而不是保存T&TRow你可以直接指向保存到该行,这取决于你。

此解决方案的一个很好的功能是您可以将 TRow 用于其他内容,例如operator int*().