[英]cannot convert from “void” to “int”
Cannot convert from "void" to "int" in C++ - anyone know why? 无法在C ++中从“ void”转换为“ int”-有人知道为什么吗? is there a function i have to use?
有必须使用的功能吗?
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);
My guess would be that one of those two functions returns a void, so you can't assign that value to an int. 我的猜测是这两个函数之一返回一个void,因此您不能将该值分配给int。 Since a "void" function doesn't return anything, you can't assign its return value to an int.
由于“ void”函数不会返回任何内容,因此无法将其返回值分配给int。
I would expect code like this to give you such an error: 我希望这样的代码会给您这样的错误:
void voidfunc () {
// Do some things
}
int main () {
int retval = voidfunc();
return 0;
}
Though my compiler gives: 虽然我的编译器给出:
$ g++ main.c
main.c: In function ‘int main()’:
main.c:6: error: void value not ignored as it ought to be
void is the same as saying no type. void等于说没有类型。 There is no information in a void.
空无一物。 You cannot convert no information into a number, hence the error.
您无法将任何信息都转换为数字,因此会出现错误。
Perhaps if you give us more information about the types of your functions, or where the exact error occurred, we can help you more. 也许如果您向我们提供有关函数类型或确切错误发生位置的更多信息,我们可以为您提供更多帮助。
Per your comments, calculate_total
is declared wrong. 根据您的评论,
calculate_total
被声明为错误。 If the function needs to return a value, it should be declared as: 如果函数需要返回值,则应将其声明为:
int calculate_total(/*...*/);
Notice the int
in front of the function name, instead of void
. 注意函数名前面的
int
,而不是void
。
And in the function body: 并在函数主体中:
int calculate_total(/*...*/)
{
int total = 0;
/* ... calculate the total */
return total; // Return the total.
}
If you insist on having a function returning void
, you can add another argument to the function: 如果您坚持让函数返回
void
,则可以向该函数添加另一个参数:
void calculate_total(int * total, /*...*/);
The function then becomes: 该函数将变为:
void calculate_total(int * total, /*...*/)
{
if (total) /* check for null pointers */
{
*total = 0;
for (/*...*/)
{
*total += /*...*/
}
}
return;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.