我可以在继承 QObject 的同时使用 QSharedData 吗?
如何在 Qt 中隐藏私有实现(隐式共享):
我的 Employee.h 标头中有 Employee.cpp 以下内容:
#include <QSharedData>
#include <QString>
class EmployeeData;
class Employee: public QObject
{
Q_OBJECT
public:
Employee();
Employee(int id, QString name);
Employee(const Employee &other);
void setId(int id);
void setName(QString name);
int id();
QString name();
private:
QSharedDataPointer<EmployeeData> d;
};
class EmployeeData : public QSharedData
{
public:
EmployeeData() : id(-1) { name.clear(); }
EmployeeData(const EmployeeData &other)
: QSharedData(other), id(other.id), name(other.name) { }
~EmployeeData() { }
int id;
QString name;
};
但是当我将 EmployeeData 移动到私有部分时,比如说 Employee.cpp 我得到: 错误:无效使用不完整类型“struct EmployeeData”
但是,如果我将定义更改为这样,它就可以正常工作:
class Employee
{
public:
Employee();
Employee(int id, QString name);
..
因此,我可以在继承 QObject 时使用 QSharedData 吗?
How do I hide the private implementation (implicit sharing) in Qt:
I have Employee.cpp the following in my Employee.h header:
#include <QSharedData>
#include <QString>
class EmployeeData;
class Employee: public QObject
{
Q_OBJECT
public:
Employee();
Employee(int id, QString name);
Employee(const Employee &other);
void setId(int id);
void setName(QString name);
int id();
QString name();
private:
QSharedDataPointer<EmployeeData> d;
};
class EmployeeData : public QSharedData
{
public:
EmployeeData() : id(-1) { name.clear(); }
EmployeeData(const EmployeeData &other)
: QSharedData(other), id(other.id), name(other.name) { }
~EmployeeData() { }
int id;
QString name;
};
But when I move EmployeeData to a private part, say Employee.cpp I get:
error: invalid use of incomplete type ‘struct EmployeeData’
However, if I change my definition to this it works fine:
class Employee
{
public:
Employee();
Employee(int id, QString name);
..
Thus, can I use QSharedData while inheriting from QObject ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用 QSharedData 时不能从 QObject 继承。 QSharedData 使用 copy-on-write 语义,并将调用 detach() 在不再共享数据时创建数据副本。为了进行复制,需要一个复制构造函数,而 QObject 不支持该复制构造函数。
pimpl (或handle-body/opaque-pointer 习惯用法)通常会为数据类提供对公共实现的引用,这就是您使用信号和槽的方式。
QSharedDataPointer 提供了大部分实现细节,但看一下也很有启发性Qt 中使用的 pimpl 习惯用法(请参阅 Q_D 和朋友)
You cannot inherit from QObject when using QSharedData. QSharedData uses copy-on-write semantics and will call detach() to create a copy of the data when it's no longer being shared. In order to do the copy, a copy-constructor is needed, which QObject does not support.
The pimpl (or handle-body/opaque-pointer idiom) will often give the data class a reference to the public implementation, which is how you're expected to work with signals and slots.
QSharedDataPointer provides most of the implementation details, but it's also quite instructive to take a look at the pimpl idiom as used in Qt (see Q_D and friends)