简体   繁体   English

Qt的Pimpl成语

[英]Pimpl idiom with Qt

I am trying to build a shared library with Qt 5.6.0 and i would like to use Pimpl. 我正在尝试使用Qt 5.6.0构建共享库,并且我想使用Pimpl。

I have one class to export and this class inherits from QGraphicsScene, which itself inherits from QObject : 我有一个要导出的类,该类继承自QGraphicsScene,而QGraphicsScene本身继承自QObject:

// CustomScene.h
#include "customscene_global.h" // recommended header from Qt
#include <QGraphicsScene> // do not compile if not present 

// forward declarations
class CustomSceneImpl;
template <typename T> class QList;
class QString;
template <class Key, class T> class QMap;
// some other classes ...

class CustomScene : public QGraphicsScene
{
  Q_OBJECT

  public :
  // some public functions

  signals:
  // some custom signals

  public slots:
  // some custom public slots

  private:
    CustomSceneImpl *m_pimpl; // pointer to private members

};

Everything's is fine if i #include <QGraphicsScene> in this header but i would prefer to forward declare QGraphicsScene. 如果我在此标头中#include <QGraphicsScene> ,一切都很好,但我希望转发声明QGraphicsScene。 However i get the following compile error if i do that : 但是,如果我这样做,则会收到以下编译错误:

error: invalid use of incomplete type 'struct QGraphicsScene'

I guess i am doing something wrong with the QObject Macro, that is not recognized, and with the moc in general. 我想我在QObject宏和一般的Moc上做错了什么,这是无法识别的。

I know there are dedicated Qt Macro to use Pimpl ( Q_D, .. ) but i did not really understand how to use them and if it would fix this issue. 我知道有专门的Qt Macro可以使用Pimpl(Q_D,..),但我并不真正了解如何使用它们以及它是否可以解决此问题。

Thanks for your help. 谢谢你的帮助。

Everything's is fine if i #include QGraphicsScene in this header but i would prefer to forward declare QGraphicsScene. 如果我在此标头中包含#include QGraphicsScene ,一切都很好,但我希望转发声明QGraphicsScene。

you cannot do it as you inherit from QGraphicsScene : QGraphicsScene继承时,您无法执行此操作:

class CustomScene : public QGraphicsScene

btw. 顺便说一句 this error has nothing to do with the way you implemented PIMPL idiom (actually it looks fine), inheritance from incomplete type is simply not possible as compiler needs to know the size / layout of your base class. 此错误与实现PIMPL惯用语的方式无关(实际上看起来不错),由于编译器需要知道基类的大小/布局,因此根本不可能从不完整的类型进行继承。

由于前向声明的类没有有关内容的信息,因此不能将其用于继承。

You can use PIMPL idiom for composition, not for inheritance. 您可以将PIMPL惯用语用于合成,而不用于继承。 If you need to inherit from QGraphicsScene , you cannot forward declare it. 如果需要从QGraphicsScene继承,则不能转发声明它。 You have to include its full definition. 您必须包括其完整定义。

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

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