繁体   English   中英

Qt项目中的前向声明

[英]Forward declaration in Qt project

我正在尝试将Qt与C ++一起使用。 我以前会使用QT在Python中进行编程。

我的简单测试无法正常工作。 这是我的tour.h文件:

#ifndef TOUR_H
#define TOUR_H

#include <QtWidgets/QMainWindow>
#include <QtWidgets/QTableView>

class TourTable;

class Tour : public QMainWindow
{
    Q_OBJECT

public:
    Tour();

/*protected:
    void closeEvent(QCloseEvent *event);

private slots:
    void newCompetitor();
    void remCompetitor();
    void finalReport();
    void openPage();
    void savePage();
    void reloadTitle();*/

private:
    TourTable _table;

};

class QStandardItem;
class QStandardItemModel;

class TourTable : public QTableView
{
    Q_OBJECT

public:
    TourTable();
/*  bool isChanged();
    QString windowName();
    void finalReport();
    void newCompetitor();
    void remCompetitor();
    bool savePage();
    void setChanged(bool value);
    void openPage();    

protected:
    void itemChanged(QStandardItem item);

private:*/
//  bool _secondBetter(p1, p2);

    Tour _parent;
//  QStandardItemModel _model;
//  bool _saved;
//  bool _changed;

};

#endif

我已经注释掉了这段代码中的几乎所有内容,以找出问题所在,但我仍然不知道是什么原因引起的。 这是我第一次尝试使用C ++。

错误消息是:

tour.h:28:12: error: field ‘_table’ has incomplete type ‘TourTable’
  TourTable _table;
            ^~~~~~
tour.h:7:7: note: forward declaration of ‘class TourTable’
 class TourTable;

有人可以帮我解决这个问题吗?

需要明确的是,此错误是由编译器而不是qmake引起的,并且是语言的限制。 但是,可以通过创建一个定义父/子行为的类并在希望该行为从基类继承的任何类上进行创建(如Qt的QObject一样)来轻松克服。

QMainWindowQTableView都继承自QObject ,因此,如果您使用QObject的父/子系统,则此设计可能是多余的。 要从子级中找到父级,请调用parent() ,并从父级中找到子级,可以调用children()

C ++中的前向声明允许在定义类型之前引用类型。 这里的问题是您的代码中:

class TourTable;

class Tour : public QMainWindow
{
    // ...

    TourTable _table;

};

您不仅要引用TourTable类型,还要使用TourTable _table;实例化它TourTable _table; 这需要TourTable的完整定义。

一种解决方案是在Tour之前定义TourTable ,如下所示:

class TourTable : public QTableView
{
    // ...

    Tour _parent;
}

class Tour : public QMainWindow
{
    // ...

    TourTable _table;
};

但这只是在移动问题,因为您要在TourTable实例化Tour

根据完整的设计,解决方案可能是使用指针。 像这样:

class TourTable;

class Tour : public QMainWindow
{
    Tour();
        // forward declaration of the constructor,
        // see below for the definition

    TourTable* _table;
        // no complete definition of TourTable at this stage,
        // only a forward declaration:
        // we can only declare a pointer
};

class TourTable : public QTableView
{
    TourTable(Tour* parent):
        QTableView(parent),
        _parent(parent)
    {
    }

    Tour* _parent;
}

Tour::Tour() // definition of Tour's constructor
{
    _table = new TourTable(this);
        // TourTable has been defined : we can instantiate it here
}

暂无
暂无

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

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