[英]cannot convert from “void” to “int”
无法在C ++中从“ void”转换为“ int”-有人知道为什么吗? 有必须使用的功能吗?
int calc_tot,go2;
go2=calculate_total(exam1,exam2,exam3);
calc_tot=read_file_in_array(exam);
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
void等于说没有类型。 空无一物。 您无法将任何信息都转换为数字,因此会出现错误。
也许如果您向我们提供有关函数类型或确切错误发生位置的更多信息,我们可以为您提供更多帮助。
根据您的评论, 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.