澄清循环依赖

时间:2016-04-30 21:56:59

标签: c++ class

我之前的帖子已被标记为重复 - https://stackoverflow.com/questions/36960042/lots-of-unreasonable-compiler-errors-c

我尝试了建议的解决方案。 但是当向前声明“class course;”时,我的编译器似乎没有识别前面文件中的类,说在“student.cpp”中提到的每个地方的课程(类)都是不完整的类型。

我是否错过了这一点?如何解决代码中的循环依赖? (上一篇文章中的代码)。

“course”在student.cpp中被标记为不完整

“student.h” -

#define _CRT_SECURE_NO_WARNINGS
#pragma once
#include <string>
#include <iostream>
#include <stdlib.h>
using namespace std;

class course;
class student{
private:
    string name;
    int id;
    string gender;
    int age;

public:
    int amountofcourses;
    student();
    ~student();

    course **courses;
};

“student.cpp” -

 #include "student.h"
    student::student(){
    courses = NULL;
    course *courses = new course;
}

“course.h” -

#include "student.h"
#pragma once

class course{

private:
    string name;
    int num;
    int amountofstudents;

public:
    course();
    ~course();

1 个答案:

答案 0 :(得分:1)

只需从student.h中删除#include "course.h",您不需要它,它会导致循环依赖,并将其添加到student.cpp,您实际需要它。

编辑:请注意,此答案是在编辑发布的代码之前编写的,以匹配我建议的一半。

相关问题