在QObject派生类中重复Q_DISABLE_COPY [英] Repeating Q_DISABLE_COPY in QObject derived classes

查看:1659
本文介绍了在QObject派生类中重复Q_DISABLE_COPY的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Qt中有一个宏,它允许声明私有拷贝构造函数和类的赋值运算符: http://qt-project.org/doc/qt-5.0/qtcore/qobject.html#Q_DISABLE_COPY

In Qt there is a macro that allows declaring private copy constructurs and assignment operators for classes: http://qt-project.org/doc/qt-5.0/qtcore/qobject.html#Q_DISABLE_COPY

据说这个宏应该用于所有QObject(特别是QWidget)派生类。

It is said that this macro should be used for all QObject (especially QWidget) derived classes.

我明白这是如何工作的,为什么它是有用的。

I understand how this works and why it is useful.

我不明白:原因是在QObject派生类中重复Q_DISABLE_COPY,而QObject已经包含Q_DISABLE_COPY,通过这样有效地防止我的派生类被复制?

What I do not understand: Is there any reason to repeat Q_DISABLE_COPY in my QObject derived classes while QObject already contains Q_DISABLE_COPY and through this effectively prevents my derived classes from being copied?

推荐答案

从尝试复制派生类可能打印的错误消息可能引用QObject而不是您的代码,因此错误可能看起来很混乱。例如,使用Visual Studio 2012编译此代码

The error message that might be printed from attempting to copy the derived class might refer to QObject instead of your code, so the error might appear to be confusing. For example, using Visual Studio 2012 to compile this code

class MyClass : public QObject
{

};

int main(int argc, char *argv[])
{
    Q_INIT_RESOURCE(application);

    MyClass obj1;
    MyClass obj2(obj1);

    QApplication app(argc, argv);
    app.setOrganizationName("QtProject");
    app.setApplicationName("Application Example");
    MainWindow mainWin;
    mainWin.show();
    return app.exec();
}

会导致此错误(以及一系列对QObject的引用) p>

results in this error (and a bunch of references to QObject).


错误:C2248:'QObject :: QObject':无法访问在'QObject'类中声明的私有成员

error: C2248: 'QObject::QObject' : cannot access private member declared in class 'QObject'

将MyClass更改为

Changing MyClass to

class MyClass : public QObject
{
private:
    Q_DISABLE_COPY(MyClass)
public:
    MyClass();
};

会导致更多的用户友好的错误组,引用MyClass,从

results in a much more user friendly group of errors that refer to MyClass, starting with


错误:C2248:'MyClass :: MyClass':无法访问私有成员
在'MyClass'类中声明

error: C2248: 'MyClass::MyClass' : cannot access private member declared in class 'MyClass'

我认为第二个错误信息对于Qt新手来说更容易理解。

I think the second error message is easier to understand for somebody that is new to Qt.

在派生类中重复定义的另一个原因是为了保护你的代码从未来的bug,如果QObject的实现改为不再使用Q_DISABLE_COPY()。虽然这是不可能的,通过记录这个要求Qt开发人员自己留下一个小量的摆动的房间,如果他们决定更改QObject。

Another reason to repeat the definition in derived classes is to protect your code from future bugs if the implementation of QObject is changed to no longer use Q_DISABLE_COPY(). While this is unlikely, by documenting this requirement the Qt developers left themselves a small amount of wiggle room if they ever decide to change QObject.

这篇关于在QObject派生类中重复Q_DISABLE_COPY的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆