簡體   English   中英

無法從“ void”轉換為“ int”

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM