我正在爲我的作業工作,因爲一些部分不是很好解釋我有一些問題,有我的結構和我的構造函數,它必須是動態的,但我得到了下游錯誤。一些幫助真的很感謝你。 .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