C++重载operator [] []

Tom*_*ora 12 c++ overloading matrix operator-keyword

我有类CMatrix,其中是值的数组"双指针".

class CMatrix {
public:
    int rows, cols;
    int **arr;
};
Run Code Online (Sandbox Code Playgroud)

我只需要输入以下内容来访问矩阵的值:

CMatrix x;
x[0][0] = 23;
Run Code Online (Sandbox Code Playgroud)

我知道如何使用:

x(0,0) = 23;
Run Code Online (Sandbox Code Playgroud)

但我真的需要这样做.任何人都可以帮助我吗?请?

谢谢大家帮忙,我这样做了...

class CMatrix {
public:
   int rows, cols;
   int **arr;

public:
   int const* operator[]( int const y ) const
   {
      return &arr[0][y];
   }

   int* operator[]( int const y )
   {
      return &arr[0][y];
   }

   ....
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助我真的很感激!

unk*_*ulu 24

你不能重载operator [][],但这里常见的习惯用法是使用代理类,即重载operator []来返回已经operator []重载的不同类的实例.例如:

class CMatrix {
public:
    class CRow {
        friend class CMatrix;
    public:
        int& operator[](int col)
        {
            return parent.arr[row][col];
        }
    private:
        CRow(CMatrix &parent_, int row_) : 
            parent(parent_),
            row(row_)
        {}

        CMatrix& parent;
        int row;
    };

    CRow operator[](int row)
    {
        return CRow(*this, row);
    }
private:
    int rows, cols;
    int **arr;
};
Run Code Online (Sandbox Code Playgroud)


Som*_*ude 18

operator[][]在C++中没有.但是,您可以重载operator[]以返回另一个结构,并在该重载中operator[]也可以获得所需的效果.