C++ C++;包括在一个循环中 请考虑以下三个简化文件: 学生h: #ifndef STUDENT_H #define STUDENT_H #include "course.h" class Student { private: Course someCourse; }; #endif #ifndef STUDENT_H #define STUDENT_H #include "course.h" class Student { private: Course someCourse; }; #endif

C++ C++;包括在一个循环中 请考虑以下三个简化文件: 学生h: #ifndef STUDENT_H #define STUDENT_H #include "course.h" class Student { private: Course someCourse; }; #endif #ifndef STUDENT_H #define STUDENT_H #include "course.h" class Student { private: Course someCourse; }; #endif,c++,include,cycle,C++,Include,Cycle,课程h: #ifndef COURSE_H #define COURSE_H #include "student.h" class Course { private: Student someStudent; }; #endif #ifndef COURSE_H #define COURSE_H class Student; class Course { private: Student* someStudent; }; #endif 和main.cpp: #in

课程h:

#ifndef COURSE_H
#define COURSE_H

#include "student.h"

class Course
{
private:
    Student someStudent;
};

#endif
#ifndef COURSE_H
#define COURSE_H


class Student;
class Course
{
private:
    Student* someStudent;
};

#endif
和main.cpp:

#include "student.h"
int main();

这不会给我带来什么
错误C2146:语法错误:缺少“;”在标识符“someStudent”之前

在一个更复杂的程序中,它会产生更多的错误(即使对于代码的正确部分也是如此)。我猜设计是错误的:
学生
包括
课程
课程
包括
学生
。我想用它来表示的是,一个学生修了几门课,一门课有几个学生(我在完整的程序中使用向量,为了简单起见,这里避免使用向量)。有什么建议可以这样做吗

先谢谢你,弗拉德

更新: 谢谢你的快速回复。在
课程
中向前声明
学生
班级(并删除
#包括“Student.h”
)似乎可以完成这项工作。 很抱歉,我认为这不重要,但事实上我在它们中使用常量指针向量(因为学生不应该控制
课程
,而
课程
不应该控制
学生
),如下所示:

向量学生;//课堂上
你不能这样做,你必须至少将其中一个转换为指针。

这是循环的,只要你分别声明
someCourse
someStudent
为类
Student
Course
的非指针成员(如你所做),因为编译器看到了
Student
的定义,所以它需要知道它的大小,也就是说,它需要知道它的所有成员的大小,包括
课程
,它是其中之一。但是要知道
课程的规模
,就需要知道
学生的规模
。这就变成了循环

所以你需要打破这个循环,至少声明其中一个为指针。例如,您可以执行以下操作:

#ifndef STUDENT_H
#define STUDENT_H

//#include "course.h" //commenting out, as it is not needed!

class Course; //this is called forward declaration

class Student
{
private:
    Course *pSomeCourse; //pointer
};

#endif
还请注意,当您将
pSomeCourse
声明为
Course*
类型的指针时,不需要包含定义了
Course
的头文件。正如我在上面的代码中所做的那样,只需向前声明类
课程
就足够了


它之所以能够工作,是因为任何类的指针大小都是相同的,编译器不需要知道类的大小,就可以知道同一类指针的大小。换句话说,编译器可以知道
sizeof(Course*)
,甚至不知道
sizeof(Course)
如果要链接两个类,则必须使用前向声明和指向其中一个类接口中声明类型的实例的指针。另一个接口可以保持不变,只要它包含成员变量类型接口的声明

课程h:

#ifndef COURSE_H
#define COURSE_H

#include "student.h"

class Course
{
private:
    Student someStudent;
};

#endif
#ifndef COURSE_H
#define COURSE_H


class Student;
class Course
{
private:
    Student* someStudent;
};

#endif
学生h:

#ifndef STUDENT_H
#define STUDENT_H

#include "course.h"

class Student
{
private:
    Course someCourse;
};

#endif
#ifndef STUDENT_H
#define STUDENT_H

#include "course.h"

class Student
{
private:
    Course someCourse;
};

#endif

除了纳瓦兹回答:

如果您想从学生成员中访问课程成员,则需要在.cpp文件中包含Course.h,在该文件中定义学生的方法

如果使用g++,则会出现类似“无效使用不完整类型”的错误。

可能重复的