简体   繁体   English

C ++中类原型的问题

[英]Trouble with class prototyping in C++

Basically my code has 2 classes: 基本上我的代码有2个类:

class teacher { 
    //has object of class course
};
class course { 
    //has object of class teacher
};

This wasn't working, as teacher was not able to access class course because it is written after class teacher. 这是行不通的,因为老师无法访问课堂课程,因为它是在课堂老师之后编写的。 So then I tried creating class prototypes. 因此,我尝试创建类原型。

class teacher;
class course;
.....
class teacher {
    //object of class course
};
class course {
    //object of class teacher
};

Still doesn't work. 仍然不起作用。 And yes i do need these classes to hold each others objects. 是的,我确实需要这些类来保存彼此的对象。 Pleasee tell me this can work the way I want it too, and I don't have to change my code. 请告诉我这也可以按照我想要的方式工作,并且我不必更改代码。 Would really appreciate some help. 非常感谢您的帮助。 Thank you. 谢谢。

Code that works for what you probably want to do: 适用于您可能想要做的代码:

teacher.h 老师

#include <vector>
using std::vector;
class Course;

class Teacher
{
vector<Course*> courses;
...
};

course.h 课程

#include <vector>
using std::vector;
class Teacher;

class Course
{
vector<Teachers*> teachers;
...
};

Note that in the source files, you will want to include both header files, as right now, Teacher does not know the functionality of Course vice versa. 请注意,在源文件中,您将要包括两个头文件,因为目前, Teacher不知道“ Course的功能,反之亦然。

I did this with raw pointers to make it easier for you to understand, but you should switch to some sort of smart pointers at some point (in this case probably weak_ptr ). 我使用原始指针来做到这一点,以使您更容易理解,但是您应该在某个时候切换到某种智能指针(在这种情况下,可能是weak_ptr )。

Btw, usually, one writes class names with major first letters. 顺便说一句,通常,人们用主要的首字母写类名。

I think you should view this as a database issue. 我认为您应该将此视为数据库问题。
Let's have another table containing teachers and courses: 我们再来一张包含教师和课程的表:

class Teacher_Course
{
  Teacher t;
  Course c;
}

The table could be represented as: 该表可以表示为:

std::vector<Teacher_Course> tc_table;

The picture would be: 图片将是:

+---------+----------+  
| Teacher | Course   |  
+---------+----------+  
| Schults | Math 1   |  
+---------+----------+  
| Schults | Calculus |  
+---------+----------+  
| Jonez   | History1 |
+---------+----------+  

This schema allows your Teacher and Course classes to be independent. 此架构允许您的TeacherCourse类是独立的。 The relationship is modeled by the Teacher_Course class. 关系Teacher_Course类建模。

Thus eliminating any circular dependencies between Teacher and Course . 这样就消除了TeacherCourse之间的任何循环依赖。

Note: to be more database friendly, you may want to have record IDs and research foreign keys 注意:为使数据库更友好,您可能需要记录ID和研究外键

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM