【问题标题】:Can't figure out why overloaded operator[] isn't getting called无法弄清楚为什么重载的 operator[] 没有被调用
【发布时间】:2026-01-26 00:05:02
【问题描述】:

我有一个课程Matrix 和一个课程RowMatrix 有一个成员变量,指向来自类Row 的对象的指针。我为MatrixRow 重载了运算符[]。但不知何故,来自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


【解决方案1】:

所以我自己想通了。 我尝试从Matrixmat[][] 调用[] 运算符,但由于matRow** Row&amp; Matrix::operator[](int i) 永远不会被调用。

【讨论】:

    【解决方案2】:

    mat[i] 给你Row*,你想调用Row::operator[],但指向Row 的指针不会自动取消引用。所以你必须手动取消引用它:(*mat[i])[j]

    【讨论】:

      最近更新 更多