在此结构下,在 2D 矩阵上使用"indexing"的 C++
c++ using "indexing" over a 2D matrix, under this structure
不知道为什么,但我得到了一个错误:在这个结构之后,我不能对矩阵进行索引,所以我不能对定义的矩阵使用"索引方法"。有人能告诉我为什么吗?或者如何修复?
Header:
const int days=31;
const int exp=6;
struct Array{
int days;
int exp;
int **M;
};
施工单位:
void constr(Array loc){
//Construct of 31*6 Matrix, were 31 nr. of days and 6 specific types:
//0-HouseKeeping, 1-Food, 2-Transport, 3-Clothing, 4-TelNet, 5-others
loc.days = days;
loc.exp = exp;
loc.M = new int*[loc.days];
for(int i=0; i<loc.days;i++ ){
loc.M[i] = new int[loc.exp];
for (int j = 0; j< loc.exp; j++){
loc.M[i][j] = 0;
}
}
}
Controller.cpp
void add(int cant,int tip, Array M){
//Adds to current day the amount to a specific type
currDay();
M[currentDay][tip] += cant; ////////////error
}
void insert(int zi,int tip,int cant, Array M){
//Adds to current day the amount to a specific type
M[zi][tip] = cant; ///////////error
}
void removeDay(int day, Array M){
for(int i = 0; i<6; i++)
M[day][i] = 0; ///////////error
//zi and tip ~ day type... for easier read.
//i need to manage the expenses of a family in a month doesn't matter which
ERROR: error: no match for 'operator[]'
UI(where constructor is used):
int main(){
Array M;
constr(M);
printMenu();
return 0;
}
您没有访问成员:
M.M[currentDay][tip]
而不是
M[currentDay][tip]
或者您可以为结构定义operator []
:
struct Array{
int days;
int exp;
int **M;
int*& operator[] (int idx) { return M[idx]; }
};
您正试图在类型数组上调用operator[]
。您需要先获取指针成员。
M.M[day][i];
也就是说:你写的不是C++,而是某种晦涩难懂的坏C。在进一步编码之前,你可能想看看书单,读一读其中的一本。
您至少有两个问题:
- 第一种是使用实际的结构作为数组,这是行不通的。使用例如
M.M[day][i]
- 第二种是,当创建数组时,通过值传递结构,这意味着它将被复制到
constr
函数中的局部变量,并且数据在调用constr
的函数中不可用。将其作为引用传递,即void constr(Array &loc)
第二个问题也可以通过在结构中使用构造函数而不是单独的函数来解决:
const int DAYS=31;
const int EXP=6;
struct Array{
int days;
int exp;
int **M;
// Constructor, called when an instance of structure/class is created
Array(){
days = DAYS;
exp = EXP;
M = new int*[days];
for(int i=0; i<days;i++ ){
M[i] = new int[exp];
for (int j = 0; j< exp; j++){
M[i][j] = 0;
}
}
}
// Destructor, called when structure/class is destroyed
~Array(){
if(M){
for(int i=0;i<days;i++){
if(M[i])
delete [] M[i];
}
delete [] M
}
}
// Copy constructor, called when instance of structure/class is copied
Array(const Array &array){
days = array.days;
exp = array.exp;
M = new int*[days];
for(int i=0; i<days;i++ ){
M[i] = new int[exp];
for (int j = 0; j< exp; j++){
M[i][j] = array.M[i][j];
}
}
}
};