Pergunta

I am trying to use a vector of strings from a header file into a different header file. I am not a professional and I certainly do not have the best codes, but could anyone help me please to compile and use the vector in my other header please ?

My codes are here : MyCourse.h :

#ifndef MYCOURSE_H
#define MYCOURSE_H

#include "MyStudent.h"
#include <iostream> 
#include <vector>
#include <string>
using namespace std;

class MyCourse 
{
public:
    vector <string> allStudents;

    void addStudent() {
        int studentCounter;
        cout << "How many students would you like to add to your class ?" << endl;
        cin >> studentCounter;

        for (int i = 0; i < studentCounter; i++) {
            string Name;
            cout << "What is the student’s name?" << endl;
            cin >> Name;
            allStudents.push_back(Name);
        }
        char ch;
        cout << "Would you like to add more students to the list ? (y or n)" << endl;
        cin >> ch;

        if (ch == 'y') {
            addStudent();
        }
    }
};

#endif

and MyStudent.h:

#ifndef MYSTUDENT_H 
#define MYSTUDENT_H 

#include <iostream> 
#include <vector>
#include <string>
using namespace std;
#include "MyCourse.h" 

class MyStudent
{
public:
    vector <double> assignScores;

void addAssignScore(){
        for (int f = 0; f < allStudents.size() ; f++) { //  allStudents is undefined
            double sc;
            cout << "What is " << allStudents[f] << "'s score in the assignment ?" << endl;
            cin >> sc;
            assignScores.push_back(sc);
        }
    }

I do not know why allStudents is undefined, when it is defined in the header file called MyCourse.h, then this header file is included in MYStudent.h header file, but still undefined.

Foi útil?

Solução

You need to pass an instance of MyCourse which contains allStudents to either the constructor of MyStudent or the member function addAssignScore.

Something like this:

void addAssignScore(const MyCourse& course){
    for (int f = 0; f < course.allStudents.size() ; f++) { 
        double sc;
        cout << "What is " << course.allStudents[f] << "'s score in the assignment ?" << endl;
        cin >> sc;
        assignScores.push_back(sc);
    }
}

I understand you want to make the deadline of the assignment, but your design is suboptimal. Your are not using the classes correctly, merely as wrappers for orthogonal containers and functions. The only relation they have, is the equal numbers of students and scores. You could just as well used a std::map<std::string, double> for that.

Edit to answer your comment:

In your main.cpp. You use it like this:

#include "MyStudent.h"
#include "MyCourse.h"
//...
int main()
{
        //...
        MyCourse course;
        course.addStudent();
        MyStudent student;
        student.addAssignScore(course);
        //...
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top