c++ - Qt 的 Pimpl 习惯用法

标签 c++ qt pimpl-idiom

我正在尝试使用 Qt 5.6.0 构建一个共享库,我想使用 Pimpl。

我有一个类要导出,这个类继承自 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

};

一切都很好,如果我 #include <QGraphicsScene>在此 header 中,但我更愿意转发声明 QGraphicsScene。但是,如果我这样做,我会收到以下编译错误:

error: invalid use of incomplete type 'struct QGraphicsScene'

我想我在使用 QObject 宏和一般的 moc 时做错了,无法识别。

我知道有专门的 Qt 宏来使用 Pimpl (Q_D, ..),但我真的不明白如何使用它们以及它是否能解决这个问题。

感谢您的帮助。

最佳答案

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

你不能这样做,因为你继承自QGraphicsScene:

class CustomScene : public QGraphicsScene

顺便说一句。此错误与您实现 PIMPL 习惯用法的方式无关(实际上它看起来不错),从不完整类型继承是不可能的,因为编译器需要知道您的基类的大小/布局。

关于c++ - Qt 的 Pimpl 习惯用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37878130/

相关文章:

c++ - 当用于 "new"初始化时, () 和 {} 是否总是等价的?

c++ - tensorflow 无效参数: In[0] is not a matrix

c++ - 如何在父窗口小部件的右侧绘画?

c++ - 无法从 Qt 中的另一个小部件访问小部件中的控件

c++ - 字符串中值的 strchr 索引

c++ - 如何使用 QDataStream 从文件中读取二进制数据?

c++ - 将 pimpl 与模板类和显式实例化模板一起使用

c++ - Pimpl 习惯用法作为模板基类

c++ - 如何以编程方式编写一些 RTF 格式的 unicode 文本?