无法弄清楚为什么没有调用重载的 operator[]
Can't figure out why overloaded operator[] isn't getting called
我得到了一个 class Matrix
和一个 class Row
。 Matrix
的成员变量是一个指向 class Row
对象指针的指针。我为 Matrix
和 Row
重载了运算符 []。但是不知何故,来自 Row
的重载运算符永远不会被调用,我不知道为什么。
示例代码:
matrix.h
class Row
{
int* value;
int size;
public:
int& operator[](int i)
{
assert(i >= 0 && i < size);
return value[i];
}
};
class Matrix
{
private:
Row **mat; // Pointer to "Row"-Vector
int nrows, ncols; // Row- and Columnnumber
public:
Row& Matrix::operator[](int i){
assert(i >= 0 && i < nrows);
return *mat[i];
}
Row** getMat() {
return mat;
}
// Constructor
Matrix(int rows, int cols, int value);
};
matrix.cpp
#include "matrix.h"
Matrix::Matrix(int rows, int cols, int value) : nrows(rows), ncols(cols){
mat = new Row*[rows];
for(int i = 0; i < rows; i++) {
mat[i] = new Row(ncols);
for(int j = 0; j < ncols; j++){
// the operator-overload of Row[] isn't getting called and I don't get why not
mat[i][j] = value;
}
}
}
int main(){
Matrix m = new Matrix(2, 2, 4);
return 0;
mat[i]
给你 Row*
,你想调用 Row::operator[]
,但指向 Row
的指针不会自动取消引用。所以你必须手动取消引用它:(*mat[i])[j]
.
所以我自己想出来了。
我试图从 Matrix
到 mat[][]
调用 []-operator,但由于 mat
是 Row**
Row& Matrix::operator[](int i)
永远不会被调用。
我得到了一个 class Matrix
和一个 class Row
。 Matrix
的成员变量是一个指向 class Row
对象指针的指针。我为 Matrix
和 Row
重载了运算符 []。但是不知何故,来自 Row
的重载运算符永远不会被调用,我不知道为什么。
示例代码: matrix.h
class Row
{
int* value;
int size;
public:
int& operator[](int i)
{
assert(i >= 0 && i < size);
return value[i];
}
};
class Matrix
{
private:
Row **mat; // Pointer to "Row"-Vector
int nrows, ncols; // Row- and Columnnumber
public:
Row& Matrix::operator[](int i){
assert(i >= 0 && i < nrows);
return *mat[i];
}
Row** getMat() {
return mat;
}
// Constructor
Matrix(int rows, int cols, int value);
};
matrix.cpp
#include "matrix.h"
Matrix::Matrix(int rows, int cols, int value) : nrows(rows), ncols(cols){
mat = new Row*[rows];
for(int i = 0; i < rows; i++) {
mat[i] = new Row(ncols);
for(int j = 0; j < ncols; j++){
// the operator-overload of Row[] isn't getting called and I don't get why not
mat[i][j] = value;
}
}
}
int main(){
Matrix m = new Matrix(2, 2, 4);
return 0;
mat[i]
给你 Row*
,你想调用 Row::operator[]
,但指向 Row
的指针不会自动取消引用。所以你必须手动取消引用它:(*mat[i])[j]
.
所以我自己想出来了。
我试图从 Matrix
到 mat[][]
调用 []-operator,但由于 mat
是 Row**
Row& Matrix::operator[](int i)
永远不会被调用。