You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复C++ Matrix类中mat(i,j)索引失效问题?

问题分析:Matrix类索引无法正常工作的原因

以下程序中mat(i, j)索引在Matrix类中存在潜在问题,且代码存在不符合C++标准的写法:

#include <iostream>
#include <stdexcept>

class Vector {
private:
    int size;
    double* data;

public:
    // Constructor
    Vector() : size(0), data(nullptr) {}
    Vector(int s) : size(s), data(new double[s])
    {
        //std::cout << "Hello, Vector!";
    }
    ~Vector() {
        delete[] data;
    }
    // Copy constructor
    Vector(const Vector& other) : size(other.size), data(new double[other.size]) {
        for (int i = 0; i < size; i++) {
            data[i] = other.data[i];
        }
    }

    // Copy assignment operator
    Vector& operator=(const Vector& other) {
        if (this != &other) {
            delete[] data;
            size = other.size;
            data = new double[size];
            for (int i = 0; i < size; i++) {
                data[i] = other.data[i];
            }
        }
        return *this;
    }

    // Accessor methods
    int getSize() const {
        return size;
    }

    double& operator[](int i) {
        return data[i];
    }    
};

class Matrix {
private:
    int rows;
    int cols;
    Vector* data;

public:
    // Constructor
    Matrix() : rows(0), cols(0), data(nullptr) {}

    // Constructor
    Matrix(int rows_, int cols_) : rows(rows_), cols(cols_), data(new Vector[rows_]) {
        for (int i = 0; i < rows_; i++) {
            data[i] = Vector(cols_);
        }
    }

    // Destructor
    ~Matrix() {
        delete[] data;
    }

    // Copy constructor
    Matrix(const Matrix& other) : rows(other.rows), cols(other.cols), data(new Vector[other.rows]) {
        for (int i = 0; i < rows; i++) {
            data[i] = other.data[i];
        }
    }

    // Copy assignment operator
    Matrix& operator=(const Matrix& other) {
        if (this != &other) {
            delete[] data;
            rows = other.rows;
            cols = other.cols;
            data = new Vector[rows];
            for (int i = 0; i < rows; i++) {
                data[i] = other.data[i];
            }
        }
        return *this;
    }

    // Accessor methods
    int getRows() const {
        return rows;
    }

    int getCols() const {
        return cols;
    }

    double &operator()(int i, int j) {
        return data[i][j];
    }

    Matrix transpose() const {
        Matrix result(cols, rows);
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                result(j, i) = data[i][j];
            }
        }
        return result;
    }

    void print(){
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                std::cout << data[i][j] << " ";
            }
            std::cout << std::endl;
        }
    }
};

int main(){
  Matrix m(2, 3);
    m(0,0) = 1;     m(0,1) = 2;     m(0,2) = 3;
    m(1,0) = 4;     m(1,1) = 5;     m(1,2) = 6;

    m.print();

    Matrix result = m.transpose();
    result.print();

  if(m(0,1) != 4){
    std::cout<<"Indexing is not working";
    std::cout<<std::endl;
  }
}

程序输出:

$ sh -c make -s
$ ./main
1 2 3 
4 5 6 
1 4 
2 5 
3 6 
Indexing is not working

缺失内容与修复方案

1. Vector类缺少const版本的operator[]重载

在Matrix的transpose(const成员函数)中,data是const Vector*类型,因此data[i]是const Vector对象。此时调用非const的operator[]不符合C++标准,会导致编译错误(部分宽松编译器可能允许,但属于未定义行为)。

添加const版本的operator[]到Vector类:

const double& operator[](int i) const {
    return data[i];
}

2. Matrix类缺少const版本的operator()重载

如果需要对const Matrix对象使用(i,j)索引访问元素,必须提供const版本的operator(),否则无法在const上下文中进行索引操作。

添加const版本的operator()到Matrix类:

const double& operator()(int i, int j) const {
    return data[i][j];
}

补充说明

main函数中的if(m(0,1) !=4)条件成立是因为判断逻辑错误:m(0,1)的值是2,而4是m(1,0)的值,并非索引功能故障。若要验证索引正确性,应改为if(m(1,0) !=4),此时不会输出错误提示。

内容的提问来源于stack exchange,提问作者user366312

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 15:44:52