我创建了myClass类,为了隐藏成员,使用了D指针,但是在编译源代码时出错。这是代码:

头文件:

class myClassPrivate;

class myClass : public QObject
{
    Q_OBJECT
public:
    myClass(QObject *parent = 0);
    ~myClass();
    ...
signals:

public slots:

private:
    myClassPrivate *d;
};

和相关的.cpp
myClass::myClass(QObject *parent):
    QObject(parent),
    d(new myClassPrivate())
{
}

myClass::~myClass()
{
    delete d;
}

class myClassPrivate
{
  public:
    myClassPrivate();
    ...some methods...
    QTextStream stream;
    QFile* m_File;
};

myClassPrivate::myClassPrivate():
    m_File(new QFile)
{
}

它说:'struct myClassPrivate'的前向声明;
无效使用不完整类型'myClassPrivate'

最佳答案

您必须先将myClassPrivate声明放入myClass构造函数中。在.cpp文件中:

class myClassPrivate
{
    // ...
};

myClass::myClass(QObject *parent):
    QObject(parent),
    d(new myClassPrivate())
{
}

您可能想在网络上查看一些解释概念和Qt的便捷宏Q_DQ_DECLARE_PRIVATE等的资源:
  • Blog post on Qt private classes and D-pointers
  • KDE Techbase on D-Pointers
  • 09-06 12:35