【问题标题】:C++: Cross reference in subclassesC++:子类中的交叉引用
【发布时间】:2016-04-02 08:36:52
【问题描述】:

在以下情况下,我遇到了交叉引用问题:

假设大学里有学生(学士、硕士):

大学.h

#pragma once

#include <QDebug>

class Student;

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

学生.h

#pragma once

class University;

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

单身汉.h

#pragma once

class Student;
class University;

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

magister.h

#pragma once

class Student;
class University;

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

实现如下所示:

大学.cpp

#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;
}

student.cpp

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

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

单身汉.cpp

#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: 错误:'struct Student' 的前向声明

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

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

/university.h:5: 错误:'struct Student' 的前向声明

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

【问题讨论】:

  • 哪个编译单元有这个错误?是否需要不同的Student 子类来证明问题?

标签: c++ qt forward-declaration cross-reference


【解决方案1】:

有人(CodeFuller)假设了一个正确的答案并将其删除。为什么?

他的回答是:

至于BachelorStudent继承自Student,我必须补充

#include "student.h"

bachelorstudent.h

的标题中

它有效。非常感谢!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-17
    相关资源
    最近更新 更多