【发布时间】:2026-01-26 00:05:02
【问题描述】:
我有一个课程Matrix 和一个课程Row。 Matrix 有一个成员变量,指向来自类Row 的对象的指针。我为Matrix 和Row 重载了运算符[]。但不知何故,来自Row 的重载运算符永远不会被调用,我不知道为什么不。
示例代码: 矩阵.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);
};
矩阵.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;
【问题讨论】:
-
Matrix::operator编译吗? -
mat[i] = new Row(ncols);和mat[i][j] = value;它不会编译。请发帖minimal reproducible example -
mat[i] = new Row(ncols);也不正确。 Mat[i] 返回对 Row 的引用,Row 类也没有构造函数。所以我会 1. 将构造函数添加到 Row 类 2. 仅使用 Row& operator[] 删除 Matrix::operator
标签: c++ pointers operator-overloading