2013-05-04 130 views
1
// main.cpp 

#include <iostream> 
#include <vector> 
#include <string> 
#include "Student.h" 

using namespace std; 

void fillVector(vector<Student>&); 
void printVector(const vector<Student>&); 

int main() 
{ 
    vector<Student> myClass; 

    fillVector(myClass); 
    printVector(myClass); 

    return 0; 
} 

void fillVector(vector<Student>& newMyClass) 
{ 
    string name; 
    char grade; 

    cout << "How many you students are in your class? "; 
    int classSize; 
    cin >> classSize; 

    for (int i=0; i<classSize; i++) 
    { 
     cout<<"Enter student name: "; 
     cin>>name; 
     cout<<"Enter student grade: "; 
     cin>>grade; 

     Student newStudent(name, grade); 
     newMyClass.push_back(newStudent); 
     cout<<endl; 
    } 
    cout<<endl; 
} 

void printVector(const vector<Student>& newMyClass) 
{ 
    int size = newMyClass.size(); 
    for (int i=0; i<size; i++) 
    { 
     cout<<"Student name: "<<newMyClass[i].getName()<<endl; 
     cout<<"Student grade: "<<newMyClass[i].getGrade()<<endl; 
     cout<<endl; 
    } 

    } 

// Student.h 

#ifndef STUDENT_H_INCLUDED 
#define STUDENT_H_INCLUDED 

#include <iostream> 
#include <string> 
using namespace std; 

class Student 
{ 
public: 
    Student(); 
    Student(string, char); 
    ~Student(); 

    string getName() const; 
    char getGrade() const; 

    void setName(string); 
    void setGrade(char); 

private: 
    string newName; 
    char newGrade; 
}; 

#endif // STUDENT_H_INCLUDED 

// Student.cpp 

#include "Student.h" 

Student::Student() 
{ 
    newGrade = ' '; 
} 

Student::Student(string name, char grade) 
{ 
    newName = name; 
    newGrade = grade; 
} 

Student::~Student() {} 

string Student::getName() const 
{ 
    return newName; 
} 

char Student::getGrade() const 
{ 
    return newGrade; 
} 

void Student::setName(string name) 
{ 
    newName = name; 
} 

void Student::setGrade(char grade) 
{ 
    newGrade = grade; 
} 

我的目的是宣佈了一個名爲CreateGradeBook類內部Student.hStudent.cpp定義它,把main.cpp的所有代碼在裏面。換句話說,我想main.cpp仍然存在,但沒有像下面的代碼;如何通過類在Student.cpp中運行代碼?

#include <iostream> 

using namespace std; 

int main() 
{ 
} 

請容忍,如果我的問題是不恰當的或脫離主題,因爲我是相當新的StackOverflow。我讀過FAQ部分,但不是全部。

回答

0

那麼這裏是一個開始

class CreateGradeBook 
{ 
public: 
    void fillVector(); 
    void printVector() const; 
private: 
    vector<Student> myClass; 
}; 

注意到你在主聲明的載體是如何成爲一個私有數據成員myClass。您宣佈的兩項功能已成爲CreateGradeBook的公開方法。還要注意,他們已經失去了參數,他們現在將在私人數據成員myClass上操作。

我會讓你去做其餘的事情。

+0

非常感謝你的專家回答@john。 我會繼續前進,併爲其他成員發佈更改後的代碼,但我認爲讓他們嘗試它會更好,特別是如果他們提出正確的更改。 – Soran 2013-05-04 22:15:42