我有 CMatrix 类,其中是指向值数组的“双指针”。
class CMatrix {
public:
int rows, cols;
int **arr;
};
我只需要通过键入以下内容来访问矩阵的值:
CMatrix x;
x[0][0] = 23;
我知道如何使用以下方法做到这一点:
x(0,0) = 23;
但我确实需要以另一种方式做到这一点。有人能帮我吗?
最后我是这样做的...
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];
}
....
你不能超载operator [][]
,但这里常见的习惯用法是使用代理类,即过载operator []
在您的 Matrix 类上返回不同类的实例,然后该实例具有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;
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)