【问题标题】:overloading double subscript operator [][] in c++ [duplicate]在c ++中重载双下标运算符[] [] [重复]
【发布时间】:2026-01-12 20:40:02
【问题描述】:

如何在 C++ 中重载双下标运算符 [][] ?

我尝试了很多方法.. 没有具体的答案在任何地方..

提前谢谢..

我试过这个..但我知道它不正确

class Matrix {

    int row;
    int col;
    int ** values;
    int ptr;

    public:
        Matrix(const int r, const int c) {

            ptr = -1;
            row = r;
            col = c;

            values = new int*[row];

            for(int i=0; i<row; i++) {

                values[i] = new int[col];
            }
        }

        int & operator[](int p) {

            if(ptr == -1)
                ptr = p;

            return values[ptr][p];

        }

};

【问题讨论】:

  • 没有像双下标operator [][]这样的东西。

标签: c++ double overloading operator-keyword


【解决方案1】:

双下标运算符[][]

C++ 中没有双下标运算符。您可以做的是重载operator[] 以返回一个也重载operator[] 的对象。这将使您能够编写m[i][j]

【讨论】:

  • 非常感谢你..那是准确和清楚的..