2014-03-13 83 views
2

自從我使用C++之後已經有一段時間了,所以請和我一起裸照。我怎樣才能在一個文件中正確地定義一個C++函數,並在不使用頭文件的情況下從另一個文件中調用它?我會使用頭文件,但我的教授告訴我們不要。我一直有很多編譯問題與我的文件,處理我的功能不存在。任何幫助表示讚賞。我的程序應該按升序對數組進行排序,使用選擇排序和使用冒泡排序的降序。如何用C++在一個文件中定義一個函數並在另一個文件中調用它?

這是我到目前爲止。這是我的司機。

Driver.cpp

#include "selection.cpp" 
#include "bubble.cpp" 

#define ArraySize 10 //size of the array 
#define Seed 1 //seed used to generate random number 
int values[ArraySize]; 

int main(int argc, char** argv) { 

    int i; 



    //seed random number generator 
    srand(Seed); 

    //Fill array with random integers 
    for(i=0;i<ArraySize;i++) 
     values[i] = rand(); 

    cout << "\n Numbers in array." << endl; 

    for(i=0;i<ArraySize; i++) 
     cout << &values[i]<< "\n"; 

    int* array_p[] = values[]; 

    //Function call for BubbleSort 
    bubblesort(array_p[], ArraySize); 

    for (i=0;i<ArraySize; i++) 
     cout << &values[i] << "\n"; 


//SelectionSort 
    selectionsort(array_p, ArraySize); 

    cout << "Numbers in ascending order." << endl; 

    for (i=0;i<ArraySize; i++) 
     cout << &values[i] << "\n"; 
    return 0; 
} 

bubble.cpp

#include <iostream> 


int* bubblesort(int values[], int size) { 

    int i, j; 

    for(i=0;i<size-1;i++){ 
     for(j=0; j<size-1; j++){ 
      if(values[j+1] > values[j]){ 
       int temp = values[j]; 
       values[j] = values[j+1]; 
       values[j+1] = temp; 

       return values; 

      } 
     } 
    } 
}; 

selection.cpp

#include <iostream> 



int *selectionsort(int values[], int size){ 


    for(int i=0; i<size-1; i++){ 
     for(int j=0; j<size; j++){ 
      if(values[i] < values[j]){ 
       int temp = values[i]; 
       values[i] = values[j]; 
       values[j] = temp; 


       return values; 
      } 
     } 

    } 
}; 

回答

1

只要寫

int* bubblesort(int values[], int size); 

在您要調用該函數的其他源文件中(在調用之前)。

請注意,如果您沒有使用頭文件,那麼您必須手動注意,如果在一個文件中更改返回類型或參數列表,則會在所有文件中進行相同的更改。

一些其他的東西:

你可能要考慮將您return語句的函數的末尾,而不是返回您做出第一個交換的瞬間。或者更好的是,函數返回void - 調用者已經知道值,因爲他只是調用該函數,所以它不會再返回它。

cout << &values[i]<< "\n";輸出每個值的地址,我想你想輸出的值而不是。

int* array_p[] = values[];並按照它的行語法錯誤,我想你的意思是:int *array_p = values; bubblesort(array_p, ArraySize);

+0

好的,謝謝你這麼多。還有一個問題。 (希望)如何在我的驅動程序中使用我的氣泡排序和選擇排序函數中定義的相同數組? – ML45

+0

這就是你現在正在做的 –

+0

好的謝謝。所以這意味着我可以擺脫'int * array_p = values'這一行,因爲我已經指向其他兩個文件的函數了? – ML45

相關問題