請考慮以下三個簡單的文件:
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