【问题标题】:C++ Includes in a cycleC++ 包含在一个循环中
【发布时间】:2011-10-08 09:49:21
【问题描述】:

请考虑以下三个简化文件:
学生.h:

#ifndef STUDENT_H
#define STUDENT_H

#include "course.h"

class Student
{
private:
    Course someCourse;
};

#endif

课程.h:

#ifndef COURSE_H
#define COURSE_H

#include "student.h"

class Course
{
private:
    Student someStudent;
};

#endif

和 main.cpp:

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


这不会编译给我
error C2146: syntax error : missing ';'在标识符“someStudent”之前

它会在更复杂的程序中产生更多错误(即使是正确的代码部分)。我猜设计是错误的:Student 包括Course 和Course 包括Student。我想用它来表示一个学生参加了几门课程,而一个课程有几个学生(我在一个完整的程序中使用了向量,为了简单起见在这里避免了它们)。有什么建议吗?

提前致谢,弗拉德。

更新: 感谢您的快速回复。 Course 类中的Student 类的前向声明(并删除#include "student.h")似乎可以完成这项工作。 抱歉,我认为这无关紧要,但实际上我在每个向量中都使用了 const 指针向量(因为学生不应该能够控制 Course 和 Course 不应该能够控制Student),如:

vector<const Student* const> students; // in Course class

【问题讨论】:

标签: c++ include cycle


【解决方案1】:

这是循环的,只要你将 someCourse 和 someStudent 分别声明为类 Student 和 Course 的非指针成员(正如你所做的那样),因为编译器会看到Student,它需要知道它的大小,这反过来意味着,它需要知道它所有成员的大小,包括Course,它就是其中之一。但是要知道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 的头文件。就像我在上面的代码中所做的那样,只需前向声明 Course 类就足够了。

之所以起作用,是因为任何类的指针的大小都是一样的,编译器不需要知道类的大小,就可以知道指针的大小 属于同一类。换句话说,编译可以知道sizeof(Course*),甚至不知道sizeof(Course)。

【讨论】:

    【解决方案2】:

    除了纳瓦兹回答:

    如果您想从 Student 的成员访问 Course 的成员,您需要在 .cpp - 文件中包含 Course.h,您可以在其中定义 Student 的方法。

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

    【讨论】:

      【解决方案3】:

      如果要链接两个类,则必须使用前向声明和指向其中一个类接口中已声明类型的实例的指针。另一个接口可以保持不变,只要它包含成员变量类型接口的声明。

      课程.h:

      #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
      

      【讨论】:

        【解决方案4】:

        你不能这样做,你必须将其中至少一个转换为指针。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-07-25
          • 2013-09-19
          • 2019-07-26
          • 2023-03-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多