请考虑以下三个简单的文件:
student.h:C++中的一个周期包括
#ifndef STUDENT_H
#define STUDENT_H
#include "course.h"
class Student
{
private:
Course someCourse;
};
#endif
course.h:
#ifndef COURSE_H
#define COURSE_H
#include "student.h"
class Course
{
private:
Student someStudent;
};
#endif
和main.cpp中:
#include "student.h"
int main();
这不会编译给我
错误C2146:语法错误:缺少';'之前标识符'someStudent'
它会在更复杂的程序中产生更多的错误(即使对于正确的代码部分)。我猜设计是错误的:Student
包括Course
和Course
包括Student
。我想用它代表的是一个学生需要几门课程,一门课程有几个学生(我在一个完整的程序中使用矢量,为了简单起见,在这里避免使用它们)。任何意见如何这将是可能的?
在此先感谢弗拉德。
更新: 感谢您的快速回复。在Course
类(和删除#include "student.h"
)Student
类的前向声明似乎做的工作。 对不起,我认为这里没什么关系,但实际上我在其中每个都使用了常量指针的向量(因为学生不应该能够控制Course
和Course
不应该能够控制Student
),如:
vector<const Student* const> students; // in Course class
[C++中的循环依赖关系]的可能重复(http://stackoverflow.com/questions/4018816/circular-dependency-in-c) – tenfour