2015-01-31 25 views
1

我最近開始瞎搞與無效,碰到一個問題與無效工作首次

這是我的代碼:

#include <iostream> 
using namespace std; 

void smallSort(); 

int main() 
{ 
    int num1, num2, num3; 
    cout << "Please enter the first number" << endl; 
    cin >> num1; 
    cout << "Please enter the second number" << endl; 
    cin >> num2; 
    cout << "Please enter the third number" << endl; 
    cin >> num3; 
    cout << "Now I will sort from smallest to biggest!" << endl; 

    smallSort(); 
    return 0; 
} 

void smallSort(int& num1, int& num2, int& num3){ 
    if(num1 > num2) 
     swap(num1, num2); 
    if(num1 > num3) 
     swap(num1, num3); 
    if(num2 > num3) 
     swap(num2, num3); 

    cout << num1 << " " << num2 << " " << num3 << endl; 
} 

我試着參數添加到smallSort在主要內部,但它說,有太多的論據。我也嘗試從void中移除參數,但是這也不起作用。任何提示或任何東西我可以閱讀將是巨大的,感謝

+2

如果你有一個論據函數,您實際上需要在調用函數時傳遞參數。另請注意,由於您在編程C++,所以void smallSort()和void smallSort(int&num1,int&num2,int&num3)這兩個函數不是相同的函數。閱讀更多關於函數重載的信息。實際上,第一個等於'void smallSort(void)'(即一個採用* no *參數的函數)。 – 2015-01-31 22:36:03

+0

此外請注意,由於您聲明瞭一個不帶參數的'smallSort'函數,並且調用不帶參數的'smallSort',所以您不會收到編譯器錯誤,而是會得到一個* linker *錯誤,指出'smallSort'未定義。而它呢,因爲你沒有定義一個不帶參數的'smallSort'函數。這是您應該查找並瞭解*聲明*和*定義*之間區別的關鍵。 – 2015-01-31 22:39:27

+0

從函數中獲取'cout'(一個函數應該是一個函數)。在調用'smallSort()'之後移動它。這是一個編程原則。它不會解決你目前的問題,但它會讓你的生活更輕鬆。例如,在'cout'的地方,你可以通過刪除'&'s來重構(刪除'&'將不會有任何行爲上的影響 – 2015-01-31 22:45:49

回答

4

你的函數定義不匹配其聲明:

void smallSort(); // <== zero args 
void smallSort(int& num1, int& num2, int& num3){ // <== three args 

那些必須精確匹配。你的聲明應改爲:

void smallSort(int&, int&, int&); 

而且你不是真正調用​​使用任何參數:

smallSort(); 

應該是:

smallSort(num1, num2, num3); 
+0

它只是第一位(聲明) ,導致了這些問題,其他所有東西都導致了這個問題,例如,很多參數錯誤 – 2015-01-31 22:41:22

+0

@richard該調用顯然也不正確 – Barry 2015-01-31 22:45:02

+0

該調用是的一切。它導致了第一個錯誤。它也會導致太多的參數編譯錯誤。 – 2015-01-31 22:46:25