我正在为我的作业工作,因为一些部分不是很好解释我有一些问题,有我的结构和我的构造函数,它必须是动态的,但我得到了下游错误。一些帮助真的很感谢你。 .H:C++ struct构造函数错误
const int days=31;
const int exp=6;
struct Array{
int days;
int exp;
int **M;
};
的.cpp:
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=malloc(loc.days*sizeof(int*));
for(int i=0; i<loc.days;i++){
loc.M[i] = malloc(loc.exp*sizeof(int));
for (int j = 0; j< loc.exp; j++){
loc.M[i][j] = 0;
}
}
}
错误:
..\src\structs.cpp: In function 'void constr(Array&)':
..\src\structs.cpp:7:36: error: invalid conversion from 'void*' to 'int**' [-fpermissive]
..\src\structs.cpp:9:40: error: invalid conversion from 'void*' to 'int*' [-fpermissive]
malloc返回void *因此显式必须将其转换为int *在您的情况。但是,为什么不使用new而不是malloc。如果你被告知使用malloc,那么很好。 – Jagannath 2012-03-28 09:52:53
typecast malloc – Jeeva 2012-03-28 09:53:59
'void constr'实际上是一个自由函数。一个合适的C++构造函数将是'Array'的成员。 – Stephan 2012-03-28 09:54:34