2010-04-30 646 views
0

不能从C++中的“void”转换为“int” - 任何人都知道为什么?有没有我必须使用的功能?不能从“void”转换为“int”

int calc_tot,go2; 
go2=calculate_total(exam1,exam2,exam3); 
calc_tot=read_file_in_array(exam); 
+1

它发生在哪一行? 'calculate_total'和'read_file_in_array'的返回类型是什么?我猜这些返回中的一个是'void'类型,你不能转换为'int',因为它没有任何意义。 – 2010-04-30 20:25:36

+2

“不能将任何东西转换为数字”的部分是你有问题吗? – 2010-04-30 20:29:00

+0

o对不起 void calculate_total(exam1,exam2,exam3); void read_file_in_array(exam); – user320950 2010-04-30 22:23:45

回答

0

void与说无类型相同。虚空中没有任何信息。你不能将任何信息转换成数字,因此是错误的。

也许如果您向我们提供有关您的功能类型或确切错误发生位置的更多信息,我们可以为您提供更多帮助。

3
go2=calculate_total(exam1,exam2,exam3); 
calc_tot=read_file_in_array(exam); 

我的猜测是这两个函数之一会返回一个void,所以您不能将该值赋给int。由于“void”函数不返回任何内容,因此无法将其返回值分配给int。

我希望这样的代码给你这样的错误:

void voidfunc() { 
    // Do some things 
} 

int main() { 
    int retval = voidfunc(); 
    return 0; 
} 

虽然我的编译器为:

$ g++ main.c 
main.c: In function ‘int main()’: 
main.c:6: error: void value not ignored as it ought to be 
+0

我只是把一个新的用我的新代码提问 – user320950 2010-04-30 23:02:53

+0

downvote的原因? – WhirlWind 2010-05-01 14:42:31

0

根据您的意见,calculate_total声明是错误的。如果函数需要返回一个值,它应该被声明为:

int calculate_total(/*...*/); 

注意的int函数名的前面,而不是void

而在函数体:

int calculate_total(/*...*/) 
{ 
    int total = 0; 
    /* ... calculate the total */ 
    return total; // Return the total. 
} 

如果你坚持有一个函数返回void,你可以换个说法添加到函数:

void calculate_total(int * total, /*...*/); 

功能就变成了:

void calculate_total(int * total, /*...*/) 
{ 
    if (total) /* check for null pointers */ 
    { 
    *total = 0; 
    for (/*...*/) 
    { 
     *total += /*...*/ 
    } 
    } 
    return; 
} 
相关问题