由类制作对象的矢量

时间:2016-12-09 11:23:37

标签: c++

我最近尝试学习如何创建矢量对象,以便代表学生的对象,包括他们的姓名和成绩。但是当我编写程序时,我遇到了一些关于使用&的错误。我不知道我的错误有什么问题。你能帮我解决一下吗?

#include <iostream>
#include <vector>
#include <string>

using namespace std;

void printvector(const vector< student>&); // fill vector.fill in student information
void fillvector(vector< student>&); // print the information of all students
class student {
    public:
        student();
        student(string, char);
        ~student();
        string getName() ;
        char getGrade() ;
        void setName(string);
        void setGrade(char);

    private:

        string newName;
        char newGrade;
};

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

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

student::~student(){ }

string student::getName() { return newName; }

char student::getGrade() { return newGrade; }

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

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



int main() {

        vector<student> myclass;
        printvector(myclass);
        fillvector(myclass);
        return 0;
}

void fillvector(vector< student>& newmyclass) {

    string name;
    char grade;

    int classsize;
    cout << "how many students are in your class?";
    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;
    }
}

void printvector( vector< student>& newmyclass) {

    unsigned int size = newmyclass.size();
    for (unsigned int i = 0; i < size; i++) {

        cout << "student name:" << newmyclass[i].getName() << endl;
        cout << endl;
        cout << "student grade" << newmyclass[i].getGrade() << endl;
        cout << endl;
    }
}

1 个答案:

答案 0 :(得分:0)

在填写之前,您似乎正在打印您的矢量。当您更换它们时问题是否已解决?

int main() {

        vector<student> myclass;
        printvector(myclass); // <--- These two lines should probably be swapped
        fillvector(myclass);  // <---
        return 0;
}