当前位置

网站首页> 程序设计 > 开源项目 > 程序开发 > 浏览文章

C++类的相互关联 - 人工智能之路

作者:小梦 来源: 网络 时间: 2024-03-31 阅读:

方法

  • 其中一个类的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;}

热点阅读

网友最爱