2012-01-25 14 views
0

我只是好奇,如果我的思維方式不正確。我的思維方式工作,還是我需要在我的代碼指針/引用?你會如何處理這個問題?在這一點上,我只是粗略勾畫。看看我的意見,我的擔憂。主要對我是否應該使用指針以及如何引用Student類中的類感到好奇。你會如何去解決這個問題?舊時尚學生/課程/學校代碼。這是我的方法:

縮短例題:做一個程序,讓你: 1)從學校 2.創建/刪除學生)創建/從學校 3.刪除課程)添加/從課程中 刪除學生4)在課程 5)打印的課程,學生是在列表打印的學生名單。

class Student 
{ 
    public: 
    string name; 
    int id; 
    Student(){};//Default Construct 
    Student(int idin,string namein) 
    { 
     id=idin; 
     name=namein; 
    } 
    void PrintClasses() 
    { 
     //Umm... I can't create a Class Vector yet because Class is declared under this.. Hmm... Not sure on this part. 
    } 
}; 


class Class 
{ 
public: 
    int id; 
    string name; 
    Student students_in_class; //Is this the right way to store students in the class? 

    Class(){};//Default Constructor 
    Class(int idin, string namein) 
     { 
     id=idin; 
     name=namein; 
     } 
    void PrintStudents() 
    { 
     for (i=0;i<students_in_class.size();i++) 
     { 
      cout<<students_in_class.id<<'\n'; 
     } 
    } 
}; 

class School 
{ 
public: 
    Vector<Student> studentlist; 
    Vector<Class> classlist; 

    //This is where you do everything. 
    void StudentAdd(int id,string name) 
    { 
     //Adds a student to the school 
     Student mystudent=Student(id,name); 
     studentlist.push_back(mystudent); 
    } 
    void StudentAdd2Course(int student_id,int course_id) 
    { 
     for (i=0;i<classlist.size();i++) 
      { 
       if(classlist[i].id==course_id) 
       { 
        //Correct Class ID Found. Now find student Id 
        for (int j=0;j<studentlist.size();j++) 
         if(studentlist[j].id==student_id) 
          classlist[i].students_in_class.push_back(studentlist[j]);//Push Student in class list 
       } 
      } 

    } 
    void StudentRemoveFromCourse(int student_id,int course_id) 
    { 
     for (i=0;i<classlist.size();i++) 
      { 
       if(classlist[i].id==course_id) 
       { 
        //Correct Class ID Found. Now find student Id 
        for (int j=0;j<studentlist.size();j++) 
         if(studentlist[j].id==student_id) 
          classlist[i].students_in_class.erase(studentlist[j]);//Push Student in class list 
       } 
      } 

    } 

    //Other functions like create class, delete class, etc 

}; 
+0

班級Class下屬性'students_in_class'不應該是'Vector '嗎? – xbonez

+0

這聽起來更像是一個數據庫而不是C++的問題... –

+0

@Kerrek - 聽起來更像是一個面試問題...... – Soren

回答

2

通常情況下,設計一些面向對象的,當我嘗試啓動簡單的類,並且讓其他班級就像傀儡一樣對他們採取行動(儘管模擬學生,但不打算打遊戲)。

在這種情況下,這是一個簡單的工作,學生是一個簡單的課程,課程包含學生,而Scool包含課程(也許是學生)。

唯一的複雜因素是印刷學生需要的課程。我想說,從概念上講,它不應該在Student類中,因爲它需要的信息比簡單的對象可以提供的更多。

說到實施它,您可以循環訪問現有數據,也可以保留額外的信息。如果您使用後者,請確保額外信息在正常系統中保持一致。

Ps。查看如何使用C++中的迭代器編寫循環。

+0

謝謝。我嘗試了這個嘗試,但是失敗了。當我把學生推回去時,我的'學生'矢量的大小不會更新。我在這裏發佈了後續問題: http://stackoverflow.com/questions/9014050/whats-wrong-with-my-logic-my-vector-or-an-object-doesnt-push-back-a-new -objec – CREW