2016-04-05 55 views
1

我有一個所謂的隨機下列變量條目不更新

private: 
     int Numbers[10]; 
     int NrHighest; 
     int NrLowest; 
     int Index; 
     int IndexH; 
     int IndexL; 

和稱爲friend void insertNumbers(隨機Random1)朋友函數`

void insertNumbers(Random Random1) 
{ 
    string line; 
    int one,two,three; 
    int columOne[10]; 
    int columTwo[10]; 
    int columThree[10]; 
    ifstream myfile("Numbers.dat"); 
    if (myfile.is_open()) 
    { 
     int i = 0; 
     while (getline (myfile,line)) 
     { 
      sscanf(line.c_str(),"%i %i %i",&one,&two,&three); 
      columOne[i] = one; 
      columTwo[i] = two; 
      columThree[i] = three; 

      i++; 
     } 
     myfile.close(); 
    } 

    else cout << "Unable to open file"; 

    switch(run) 
    { 
     case 0 : 
     { 
      for(int i = 0;i < 10;i++) 
      { 
       Random1.Numbers[i] = columOne[i]; 
       cout << Random1.Numbers[i] << endl; 
      }; 
      break; 
     } 
     case 1 : 
     { 
      for(int i = 0;i < 10;i++) 
      { 
       Random1.Numbers[i] = columTwo[i]; 
       cout << Random1.Numbers[i] << endl; 
      }; 
      break; 
     } 
     case 2 : 
     { 
      for(int i = 0;i < 10;i++) 
      { 
       Random1.Numbers[i] = columThree[i]; 
       cout << Random1.Numbers[i] << endl; 
      }; 
      break; 
     } 
    } 

    run ++; 
}; 

我有一個類cout << Random1.Numbers[i] << endl;檢查號碼是否保存到Random1.Numbers,輸出是 Output

但問題來了,當我嘗試在這裏

cout << Random1; 
cout << Random2; 
cout << Random3; 

顯示對象調用重載函數,這也是友元函數friend ostream &operator<<(ostream &output,const Random & Random1);

ostream &operator<<(ostream &output,const Random & Random1) 
{ 
    for(int i = 0;i<10;i++) 
    { 
     cout << Random1.Numbers[i] << " "; 
    } 
    cout << endl << Random1.NrHighest << endl << Random1.NrLowest << endl << Random1.Index << endl << Random1.IndexH << endl << Random1.IndexL << endl; 
    return output; 
}; 

我得到的Defauts值這裏設置

Random() 
     { 
      Numbers = {0,0,0,0,0,0,0,0,0,0}; 
      NrHighest = 0; 
      NrLowest = 0; 
      Index = 0; 
      IndexH = 0; 
      IndexL = 0; 
     }; 

而不是新值,繼承人超載運算符的輸出< <函數Output

我似乎搞清楚爲什麼對象沒有得到更新。如果你想了解更多信息,請詢問。 在此先感謝。

+0

您忘記了在'void insertNumbers(Random Random1)'中通過引用傳遞參數。使它成爲'void insertNumbers(Random&Random1)'。投票結束爲錯字。 – NathanOliver

回答

1

在您的函數void insertNumbers(Random Random1)中,您正在爲Random1添加值,但是您正在按值傳遞值。因此,當這個函數被Random實例調用時,它會複製它,爲它添加值並最終銷燬它。您將通過傳遞Random1作爲參考來解決此問題:void insertNumbers(Random &Random1)

+0

輝煌我被困在這個路上很長時間,它現在非常完美,非常感謝 – Divinator