[英]Getting and Setting 2D Array Object Values (C++)
我是C ++的新手,2D数组的工作方式使我感到困惑。 我一直在网上阅读并试图了解是什么导致了我的特定问题,但是却一无所获。
根据这个Stack Overflow的答案 ,我应该能够通过以下操作在2D数组中获取一个值: (*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;
}
矩阵
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];
}
}
};
矩阵文件
#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()
。
int
时,您将无法返回对double
的引用 。 但是即使修复了该问题,您可能还会遇到其他问题。
new
)数组。 没问题,但是。
您不需要行和cols值的任何setter。 或者,您需要以以下方式更改这些设置器,即重新分配新的矩阵以适合新的大小。
#include
与复制并粘贴命名文件的内容相同。 而且您有一个uint的typedef,它只需将复制内容从matrix.h粘贴到matrix.cpp和main.cpp,因此即使您不再指定它,它也能正常工作。
您具有正在using namespace std
,但不包括std标头。 您可能需要该东西,例如,如果您#include <iostream>
或<vector>
或任何其他标准库头文件。 或者,由于某种原因,您在自己的namespace std {...}
块中编写了代码。
matrix[row][col]
是正确的方法,因为matrix
是一个int**
,并且两次应用operator[]
就像两次将指针递减一样,您将获得一个单独的int
。
出现错误的原因是at
由于返回了double&
。 让我解释一下, matrix[row][col]
返回一个int
,该int
被提升为 double
。 那个double
是一个临时变量,您不能从该临时变量中进行引用,这就是编译器抱怨的原因。
使得at
返回int&
显然会解决它:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.