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

标签 c++ operator-overloading

<分区>

Possible Duplicate:
Operator[][] overload

我制作的类包含一个数组,其中包含(在一行中)给定二维数组中的所有数字。例如给定:{{1,2}{3,4}} T 类的对象中的 b 字段包含 {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

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

    };

最佳答案

你不能。您必须重载 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);
    }
};

不是在 TRow 中保存 T&,您可以直接保存指向该行的指针,这由您决定。

这个解决方案的一个很好的特性是您可以将 TRow 用于其他事情,例如 operator int*()

关于c++ - 如何为表示动态分配的二维数组的类重载 [][] 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14653245/

相关文章:

c++ - 在 C++ 中重载 new、delete

c++ - 为所有枚举类型重载运算符 >>

C++ - 试图重载 "<<"运算符

c++ - 如何使用对象指针而不是对象来编写赋值运算符/复制构造函数?

c++ - 将 libstdc++ 静态链接是一个好习惯吗?

c++ - 是否可以存储迭代器?

c++ - 链表中的运算符重载 <<

python : Operator Overloading a specific type

c++ - dynamic_cast 向下转型 : How does the runtime check whether Base points to Derived?

C++ 嵌套命名空间别名可能吗?