首页 > 解决方案 > 重载 [] 运算符 c++

问题描述

我正在尝试为 c++ 类重载索引运算符,但我无法这样做。当我尝试索引我的 Matrix 类时,我收到以下错误:

错误:无法在初始化中将 'Matrix' 转换为 'double*'

这个错误发生在我的 main.cpp 的第 9 行。似乎编译器似乎无法识别索引?

下面是我的代码:

矩阵.h

#ifndef MATRIX_H
#define MATRIX_H

#include <iostream>

using namespace std;

class Matrix
{
    public:
        /** Default constructor */
        Matrix(unsigned int num_cols, unsigned int num_rows);
        /** Default destructor */
        virtual ~Matrix();

        /** Access num_cols
         * \return The current value of num_cols
         */
        unsigned int getCols() { return _num_cols; }

        /** Access num_rows
         * \return The current value of num_rows
         */
        unsigned int getRows() { return _num_rows; }

        double operator[](unsigned int index);

    protected:

    private:
        unsigned int _num_cols; //!< Member variable "num_cols"
        unsigned int _num_rows; //!< Member variable "num_rows"
        double ** _base;
};

#endif // MATRIX_H

矩阵.cpp

#include "Matrix.h"
Matrix::Matrix(unsigned int num_cols, unsigned int num_rows){
    _num_cols = num_cols;
    _num_rows = num_rows;

    if(_num_cols > 0) {
        _base = new double*[_num_cols];
        for(unsigned int i = 0; i < _num_cols; i++) {
            _base[i] = arr;
            cout << _base[i] << endl;
        }
    }

}

double* Matrix::operator[](int index) {
    if (index >= _num_cols) {
        cout << "Array index out of bound, exiting";
        exit(0);
    }
    return _base[index];
}

Matrix::~Matrix()
{
    //dtor
}

主文件

#include <iostream>
#include "Matrix.h"

using namespace std;

int main()
{
    Matrix * m = new Matrix(1,2);
    double * d = m[1];
    delete m;
    return 0;
}

标签: c++matrix

解决方案


重载的运算符成员函数的声明与定义不匹配。

您将运算符定义为:

double* Matrix::operator[](int index) {

但将其声明为:

double operator[](unsigned int index);

声明应为:

double *operator[](int index);

此外,这一行的问题:

double * d = m[1];

那是指m向 a 的指针,Matrix并且[]运算符在类实例上工作,而不是指向它的指针,因此您需要取消引用m

double * d = (*m)[1];

或者您可以定义m为 a 的实例Matrix

Matrix m(1,2);
double * d = m[1];

推荐阅读