c++ - 重载 [] 运算符 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;
}
解决方案
重载的运算符成员函数的声明与定义不匹配。
您将运算符定义为:
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];
推荐阅读
- spring-mvc - 如何在 Spring 组件类中访问 HttpServletRequest
- angular - agm-map 动态显示/更新标记不起作用
- html - Bootstrap 4 img-fluid:如何在轮播中为移动设备上的图像制作一致的高度
- python - 使用 Python 压缩和格式化添加到 Word 文档中的照片
- json.net - Json.Net - 匿名类型的部分反序列化
- javascript - 选择第二个孩子并赋予 ID - Javascript
- dart - Dart:使用 Observatory 查找内存泄漏
- outlook-addin - 在 Outlook 中,如何在单独的窗口中关闭消息?
- angular - 如何检索json值并存储在变量angular 4中
- python - 为什么我不能右键单击删除按钮?