无法从“void”转换为“int”

时间:2010-04-30 20:21:17

标签: c++

在C ++中无法从“void”转换为“int” - 有谁知道为什么?有必要使用的功能吗?

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

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

答案 2 :(得分: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;
}
相关问题