简体   繁体   中英

Trouble with class prototyping in C++

Basically my code has 2 classes:

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.

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 ).

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. The relationship is modeled by the Teacher_Course class.

Thus eliminating any circular dependencies between Teacher and Course .

Note: to be more database friendly, you may want to have record IDs and research foreign keys

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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