繁体   English   中英

C ++:子类中的交叉引用

[英]C++: Cross reference in subclasses

在以下情况下,我在交叉引用方面遇到了麻烦:

假设大学里有学生(学士,魔术师):

大学

#pragma once

#include <QDebug>

class Student;

class University : public QObject
{
    Q_OBJECT
public:
    explicit University(QObject *parent = 0);
    QList<Student*> students;
};

学生

#pragma once

class University;

class Student : public QObject
{
    Q_OBJECT
public:
    explicit Student(QString name,  University *parent = 0);
};

学士学位

#pragma once

class Student;
class University;

class BachelorStudent : public Student
{
    Q_OBJECT
public:
    explicit BachelorStudent(QString name, University *parent = 0);
};

魔导师

#pragma once

class Student;
class University;

class MagisterStudent : public Student
{
    Q_OBJECT
public:
    explicit MagisterStudent(QString name, University *parent = 0);
};

实现看起来像这样:

大学

#include "university.h"
#include "bachelorstudent.h"
#include "magisterstudent.h"
#include "student.h"

University::University(QObject *parent) : QObject(parent) {
    students.append(new BachelorStudent("tommy", this));
    students.append(new MagisterStudent("bobby", this));
    qDebug() << students;
}

学生.cpp

#include "student.h"
#include "university.h"

Student::Student(QString name, University *parent) : QObject(parent) {
    setObjectName(name);
}

学士学位课程

#include "bachelorstudent.h"
#include "student.h"
#include "university.h"

BachelorStudent::BachelorStudent(QString name, University *parent) : Student(name, parent)
{}

magisterstudent.cpp

#include "magisterstudent.h"
#include "student.h"
#include "university.h"

MagisterStudent::MagisterStudent(QString name, University *parent) : Student(parent)
{}

...和简单的主程序:

#include <QApplication>
#include "university.h"

int main(int argc, char *argv[]) {
    QApplication a(argc, argv);
    new University(&a);
    return a.exec();
}

不幸的是,编译器抛出:

在来自university.cpp:2的文件中:

/bachelorstudent.h:7:错误:无效使用了不完整的类型'struct Student'

/university.h:5:错误:“结构学生”的前向声明

在university.cpp:3包含的文件中:

/magisterstudent.h:7:错误:无效使用了不完整的类型'struct Student'

/university.h:5:错误:“结构学生”的前向声明

这意味着在循环依赖的情况下不正确的前向类声明。 根据许多问答论坛,“在标头中转发,包括在cpp文件中”是避免任何可能出现问题的最佳做法。 那么我的代码有什么问题呢?

有人(CodeFuller)认为正确的答案并将其删除。 为什么?

他的回答是:

至于BachelorStudent是从Student继承的,我必须添加

#include "student.h"

bachelorstudent.h的标题中

有用。 非常感谢!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM