简体   繁体   中英

Pimpl idiom with Qt

I am trying to build a shared library with Qt 5.6.0 and i would like to use Pimpl.

I have one class to export and this class inherits from QGraphicsScene, which itself inherits from 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. 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.

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.

Thanks for your help.

Everything's is fine if i #include QGraphicsScene in this header but i would prefer to forward declare QGraphicsScene.

you cannot do it as you inherit from 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.

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

You can use PIMPL idiom for composition, not for inheritance. If you need to inherit from QGraphicsScene , you cannot forward declare it. You have to include its full definition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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