【发布时间】:2015-08-16 14:46:40
【问题描述】:
当我注意到以下问题时,我正在做一些 C++ 练习。 给定的代码不会在 Visual Studio 2013 或 Qt Creator 5.4.1 中运行/编译
给出错误:
invalid types 'double[int]' for array subscript
test[0][0] = 2;
^
但是,当您第一次将头文件中的第 16(和第 17)行从
double &operator[]; 到 double operator[] 并在源文件中进行相同的更改 -> 然后编译它(同时出现多个错误) -> 最后将其更改回原来的 double &operator[];。然后在 Qt Creator 5.4.1 中,它将编译并运行,同时给出预期的结果。
编辑:这并不总是有效,但是将其更改为 double *operator[] 而不是 double operator[] 总是会重现问题。
为什么会这样?
矩阵.h
#ifndef MATRIX_H
#define MATRIX_H
#include <iostream>
using namespace std;
class Matrix
{
private:
double** m_elements;
int m_rows;
int m_columns;
public:
Matrix(int rows = 1, int columns = 1);
double &operator[](int index);
const double &operator[](int index) const;
friend ostream &operator<<(ostream &ostr, Matrix matrix);
};
#endif // MATRIX_H
矩阵.cpp
#include "matrix.h"
Matrix::Matrix(int rows, int columns)
{
m_rows = rows;
m_columns = columns;
m_elements = new double*[rows];
for(int i=0; i<rows; i++)
{
m_elements[i] = new double[columns];
for(int j=0; j<columns; j++)
m_elements[i][j] = 0;
}
}
double &Matrix::operator[](int index)
{
return *(m_elements[index]);
}
const double &Matrix::operator[](int index) const
{
return *(m_elements[index]);
}
ostream &operator<<(ostream &ostr, Matrix matrix)
{
for(int i=0; i<matrix.m_rows; i++)
{
for(int j=0; j<matrix.m_columns; j++)
{
ostr << matrix.m_elements[i][j] << " ";
}
ostr << "\n";
}
return ostr;
}
主要
#include <iostream>
#include "matrix.h"
using namespace std;
int main()
{
Matrix test(4,4);
test[0][0] = 2;
cout << test;
return 0;
}
【问题讨论】:
-
我已经做了几十年了,但从来不敢写
*m_elements[index];。你知道是先申请*还是[]?我不! :-) 我会根据预期的顺序写*(m_elements[index]);或(*m_elements)[index];。 -
感谢您的提示(它确实像我预期的那样使用了
*(m_elements[index]);,但可能在不同的编译器上不会出现这种情况),我编辑了我的文件,但这仍然不能解决问题我有。 -
我很确定从
operator[]返回一个对双重对象的引用不是你想要做的。如果operator[]应该在您的矩阵中提供 row 的基数,则您应该返回简单的m_elements[index],返回类型为double*,或者double *&,如果您真的想要直接引用m_elements[index]处的指针(我不建议这样做)。
标签: c++ qt visual-studio-2013 qt-creator