2013-05-08 52 views
1

即時通訊編程新手,但是我已經在java中做了一些編程,所以我並不是全新的OO編程。轉換爲非標量類型請求

我想要做的是創建結構,然後是該結構的對象數組。我試圖保持數組始終排序(使用新手排序),所以我所做的是定義結構,然後創建該結構的數組[50],並幫助該結構的變量。然後,我從用戶中獲得的每個新變量的不同變量(名稱,姓氏,成績等等)都輸入到輔助變量中。然後,當用戶輸入完輔助變量中的所有數據後,我繼續計算數組中應放置哪個對象的位置。

這裏是示例代碼,虐待儘量保持它儘可能簡單。

struct student { 
    //declaring variables that student should have 
}; 

student students[50]; 
int numOfStud=0; 

while (a=='y' && numofStud<50) { //a=='y' just means user wants to add more students 
    student input= new student; 
      //adding various data to student  
      //adding input into an array of students using variation of insertion sort algorithm 
cout << "want to add more students?"; 
cin >> a; 
} 

當我嘗試編譯這個時,我在student input= new student得到錯誤。所以我現在有點困惑。

偏題:另外我有一個關於當你做什麼時會發生什麼的問題students[0]=input;我在這裏創建對象的另一個副本,或者我只是創建另一個指針(如在java中),因此兩個學生[0]並且輸入將指向相同的對象?

感謝您的幫助!

回答

6

new T成功調用返回指向一個動態分配的T對象,所以你正試圖從一個指針實例化一個studentstudent這裏:

student input= new student; 

你只需要

student input; 

當你做

students[0]=input; 

您正在將input的值分配到位於students[0]中的student實例中。所以students[0]input將是不同的對象。

+0

真棒,清除它給我。再次感謝。 :D還要感謝所有其他答案。 – 2013-05-08 15:45:41

2

new關鍵字是用於使用指針在上分配內存。你只需要

student input; 
// fill "input" with data 
相關問題