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.h并在其中定义它Student.cpp并将所有代码main.cpp放入其中。换句话说,我想main.cpp仍然在那里,但没有像下面这样的代码;

#include <iostream>

using namespace std;

int main()
{
}

如果我的问题不恰当或离题,请多多包涵,因为我对 StackOverflow 还很陌生。我已经阅读了常见问题部分,但不是全部。

4

1 回答 1

0

好吧,这是一个开始

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

请注意您在 main 中声明的向量如何成为私有数据成员myClass。您声明的两个函数已成为CreateGradeBook. 另请注意,它们丢失了参数,而是现在对私有数据成员进行操作myClass

我会让你做剩下的。

于 2013-05-04T19:55:30.360 回答