gpt4 book ai didi

c++ - 如何在不同的头文件中使用头文件的 vector ?

转载 作者:行者123 更新时间:2023-11-28 00:32:37 26 4
gpt4 key购买 nike

我正在尝试将一个头文件中的字符串 vector 用于另一个头文件。我不是专业人士,我当然没有最好的代码,但是有人能帮我编译并在我的其他 header 中使用 vector 吗?

我的代码在这里:我的类(class).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

和 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);
}
}

不知道为什么allStudents是undefined,当它在名为MyCourse.h的头文件中定义时,那么这个头文件包含在MYStudent.h头文件中,但仍然是undefined。

最佳答案

您需要传递 MyCourse 的实例其中包含 allStudentsMyStudent 的构造函数或者成员函数 addAssignScore .

像这样:

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);
}
}

我知道您想在最后期限前完成作业,但您的设计并不理想。您没有正确使用这些类,它们只是作为正交容器和函数的包装器。他们唯一的关系是学生人数和分数相等。你也可以使用 std::map<std::string, double>为此。

编辑以回答您的评论:

在你的 main.cpp 中。你可以这样使用它:

#include "MyStudent.h"
#include "MyCourse.h"
//...
int main()
{
//...
MyCourse course;
course.addStudent();
MyStudent student;
student.addAssignScore(course);
//...
}

关于c++ - 如何在不同的头文件中使用头文件的 vector ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22236006/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com