方法
其中一个类的hpp,cpp都正常写,也就是hpp引用另一个类,cpp引用自己的hpp
另一个类,hpp中声明关联类,cpp中引用关联类
示例
/* Teacher.hpp */
#ifndef Teacher_hpp
#define Teacher_hpp
#include <stdio.h>
#include "Student.hpp"
class Teacher {
public:
Student * students;
};
#endif /* Teacher_hpp */
/* Teacher.cpp */
#include "Teacher.hpp"
/* Student.hpp */
#ifndef Student_hpp
#define Student_hpp
#include <stdio.h>
//#include "Teacher.hpp"
class Teacher;
class Student {
public:
int number;
Teacher * teacher;
Teacher * getTeacher();
};
#endif /* Student_hpp */
/* Student.cpp */
#include "Teacher.hpp" // 只需要导入关联类的头文件,因为里面包含Student.hpp
//#include "Student.hpp"
Teacher * Student::getTeacher() {
return teacher;
}
/* main.cpp */
#include <iostream>
#include <stdio.h>
#include "Teacher.hpp"
#include "Student.hpp"
using namespace std;
int main() {
// 随便做点儿什么
Teacher teacher;
Student students[10];
teacher.students = students;
for (int i = 0; i < sizeof(students) / sizeof(Student); i++) {
teacher.students[i].number = i;
teacher.students[i].teacher = &teacher;
cout << i << endl;
}
cout << sizeof(students) << endl;
return 0;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。