【问题标题】:passing in a class instance as another class parameter传入一个类实例作为另一个类参数
【发布时间】:2014-02-23 17:08:17
【问题描述】:
Course newCourse(id,instructor[id2],name,dept);
Course::courseList.insert(std::pair<int,Course>(id,newCourse));

这是我调用课程类的构造函数的代码部分。讲师[id2] 是我认为它可能起作用的方式,但事实并非如此。

 Course(int courseId, Instructor instructor, string courseName, string   dept)
 :courseId(courseId),instructor(instructor),courseName(courseName),dept(dept)
 {
 };

这是类定义中的代码 sn-p。如您所见,其中 3 个参数是一个 int 和 2 个字符串。我知道如何很好地通过那些,但它是我坚持的讲师讲师的论点。

Instructor 类将每个人的信息存储在以 int 为键的地图中。我从构建课程类中读取的文件使用 int 将课程与讲师联系起来。我想我会使用 int 并查看讲师地图以提取正确的人的姓名,但我不断收到未定义的函数错误。

文件中的示例:

0,0,Science,Dept
the first 0 s the course ID number and the second is the instructor ID number.

编辑:不同的方法似乎是相同类型的调用

相关方法的代码

224             string myText(line);
225             istringstream iss(myText);
226             if (!(iss>>id)) id = 0;
227             iss.ignore(1,',');
228             if (!(iss>>id2)) id2 = 0;
229             cout<<"id: "<<id<<" id2: "<<id2<<endl;
230             Enrollment newEnrollment(Course::courseList[id], Student::studentList[id2]);

构造函数声明:

 87         Enrollment(Student student,Course course):student(student),course(course){}

错误:

:在静态成员函数`static int Enrollment::loadEnrollment()

230:错误:没有匹配函数调用 `Enrollment::Enrollment(Course&, Student&)'

81:错误:候选人是:Enrollment::Enrollment(const Enrollment&)

88: 错误:Enrollment::Enrollment()

87: 错误:Enrollment::Enrollment(Student, Course)

【问题讨论】:

  • 编译器输出是什么?
  • project1.cc: 在静态成员函数`static int Course::loadCourses()': project1.cc:189: error: no match for 'operator[]' in 'instructor[id2]'
  • 你能发布导师的声明和从文件中加载导师的代码吗?
  • 声明是指加载课程方法开头的 Instructor 讲师?
  • @TAS 我已经添加了我相信你要求的内容。

标签: c++ class map


【解决方案1】:

您正在尝试访问名为instructor 的变量上的operator[]。此变量未定义此运算符。这就是给你编译错误的原因。

加载的讲师位于Instructor::instructorList 变量中,如从文件加载讲师的代码所示。

要解决此错误,您必须更改包含 instructor[id2] 的行以改为使用列表:

Course newCourse(id,Instructor::instructorList[id2],name,dept);

【讨论】:

  • 好的,可以编译。我有一个循环打印出地图的内容,所以我将运行它来测试并查看所有内容是否正确加载。我会尽快回来报告。
  • 一切似乎都按照我的意愿运行。谢谢!!
猜你喜欢
  • 1970-01-01
  • 2023-01-18
  • 1970-01-01
  • 2012-10-18
  • 2016-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-19
相关资源
最近更新 更多