【发布时间】:2016-07-09 04:00:52
【问题描述】:
我是 C++ 新手,二维数组的工作方式让我很困惑。我一直在网上阅读并试图了解导致我的具体问题的原因,但一无所获。
According to this Stack Overflow answer,我应该能够通过这样做在我的二维数组中获取一个值:(*myArrayObject)[row][col],但它会引发以下错误:
error: invalid types 'int[unsigned int]' for array subscript
return (*myArrayObject)[row][col];
^
如果我尝试执行myArrayObject[row][col],则会引发以下错误:
error: invalid initialization of non-const reference of types 'double&' from an rvalue of type 'double'
return myArrayObject[row][col];
^
这是有问题的完整(相关/简洁)代码:
main.cpp
#include "matrix.h"
using namespace std;
typedef unsigned int uint;
int main() {
Matrix * matrix; //This could be the problem, but not sure what else to do
matrix = new Matrix(10, 1);
for(uint i = 0; i < matrix->numRows(); ++i) {
for(uint j = 0; j < matrix->numCols(); ++j) {
cout << matrix->at(i,j) << " " << endl;
}
}
return 0;
}
matrix.h
typedef unsigned int uint;
class Matrix {
public:
Matrix(uint rows, uint cols); //Constructor
const uint numRows() const;
const uint numCols() const;
void setRows(const uint &);
void setCols(const uint &);
double & at(uint row, uint col);
private:
uint rows, cols;
int ** matrix; //This could also be the problem, but not sure what else to do
void makeArray() {
matrix = new int * [rows];
for(uint i = 0; i < rows; ++i) {
matrix[i] = new int [cols];
}
}
};
matrix.cpp
#include "matrix.h"
typedef unsigned int uint;
Matrix::Matrix(uint rows, uint cols) {
//Make matrix of desired size
this->setRows(rows);
this->setCols(cols);
//Initialize all elements to 0
for(uint i = 0; i < rows; ++i) {
for(uint j = 0; j < cols; ++j) {
this->matrix[i][j] = 0;
}
}
}
const uint Matrix::numRows() const {
return this->rows;
}
const uint Matrix::numCols() const {
return this->cols;
}
void Matrix::setRows(const uint & rows) {
this->rows = rows;
}
void Matrix::setCols(const uint & cols) {
this->cols = cols;
}
double & Matrix::at(uint row, uint col) {
return matrix[row][col]; //NOT WORKING
}
解决方案:
对 matrix.h 所做的更改:
double ** matrix;
void makeArray() {
matrix = new double * [rows];
for(uint i = 0; i < rows; ++i) {
matrix[i] = new double [cols];
}
}
对 matrix.cpp 的更改:
在构造函数中添加了makeArray()。
【问题讨论】:
-
myArrayObject[row][col]似乎是晚餐的食物,但坦率地说,我会使用单维std::vector<double>并在at成员中进行行/列数学运算以获得正确的元素。顺便说一句,您将很难从声明为int的矩阵中返回double &。
标签: c++ arrays object matrix multidimensional-array