2012-02-21 33 views
0

所以我想使用排序功能(類似於泡沫),並傳遞到它的對象。如果該對象更大(按字母順序),然​​後切換然後返回true並將其切換到之前。我不斷收到內部mySort() if語句該說「不匹配的operator []在ARR [J]。」但是從我的理解我傳遞一個對象數組內的權利,雖然錯誤?爲什麼會發生這種情況,我該如何解決它?敵不過運營商[]

這裏的驅動器

#include <iostream> 
#include <fstream> 
#include <string> 
#include "phoneEntry.h" 
using namespace std; 

void mySort(PhoneEntry &arr, int size) 
{ 
    bool inOrder = false; 
    string temp; 
    for (int i = size - 1; i > 0 && !inOrder; i--) 
    { 
     inOrder = true; 
     for (int j = 0; j < i; j++) 
     { 
      if(arr.alphaGreater(arr[j])) 
      { 
       inOrder = false; 
       temp = arr[j]; 
       arr[j] = arr[j + 1]; 
       arr[j + 1] = temp; 
      } 
     } 
    } 
}; 

int main() 
{ 
    const int MAXNUM = 500; 
    PhoneEntry entry[MAXNUM]; 
    ifstream filezilla; 
    filezilla.open("phone.txt"); 
    int count = 0; 

    if(filezilla) 
    { 
     while(count < MAXNUM && entry[count].readEntry(filezilla)) 
     { 
      count++; 
      mySort(entry[count], count); 
     } 

     for(int i = 0; i < count; i++) 
     { 
      entry[i].writeEntry(cout) << endl; 
     } 
    } 
    else 
    { 
     cout << "404" << endl; 
    } 

    return 0; 
} 

Phone Entry Header

Phone Number Header

排序文本(http://pastebin.com/HE8Rsmbg)

+3

不,你傳遞的是一個'PhoneEntry'對象的引用 – 2012-02-21 20:32:55

+0

'entry [count]'是一個'PhoneEntry'。函數'mySort'沒有按值(複製)取值,它通過引用來獲取它,這是更高效的,並且允許您修改它,如果需要的話。 – 2012-02-21 21:03:04

回答

4
  1. arr應該是一個數組,不是一個參考,像這樣PhoneEntry arr[]

  2. 你應該通過整個數組排序,而不是一個單一的元素,像這樣:mySort(entry, count);

除此之外,您的代碼出現確定。

我應該補充說,這不是一個C++ - ish解決方案:在C++中管理數組的首選方法是使用標準庫中的std::vector<T>容器。關於矢量的好處在於,你不需要將「尺寸」傳遞給它們。

+0

謝謝!這解決了我的問題,但顯然我仍然有更多的xD + 1 – 2012-02-21 21:19:34

1

arr是不是在你的方法數組。

你的方法的簽名更改爲

void mySort(PhoneEntry *arr, int size)

mySort(entry[count], count);

1

從我的理解我傳遞一個對象數組權打電話給你的方法是什麼?

不,你不能傳遞一個對象數組。您正將參考(由功能標頭中的&表示)傳遞給位於entry陣列中count第012位的PhoneEntry元素。你可能在mySort頭意味着PhoneEntry* arr - 這將需要一個指向PhoneEntry實例,因爲數組的名字可以被解釋爲指針,數組的第一個元素,你可以簡單地通過entry作爲第一參數爲mySort

0

替補這樣的:

void mySort(PhoneEntry * arr, int size) 

取而代之的是:

// Wrong 
mySort(entry[count], count); 

...做這些中的一個(如適用):

// Always passes the start of the array, "entry[0]": 
mySort(entry, count); 

// Passes a pointer to a particular entry, onwards: 
mySort(&entry[count], count); 
2

您可以使用
指針符號 - mySort(PhoneEntry * arr, int size)
或數組符號 - mySort(PhoneEntry arr[], int size)

如果要在調用該函數時傳遞整個數組,請執行mySort(entry, count)