Qt编译错:cannot access private member declared in class 'QObject'

时间:2023-01-15 15:31:54

1>u:/source/hitemfile.h(174) : error C2248: 'QObject::QObject' : cannot access private member declared in class 'QObject'
1>        d:/qt/include/qtcore/../../src/corelib/kernel/qobject.h(302) : see declaration of 'QObject::QObject'
1>        d:/qt/include/qtcore/../../src/corelib/kernel/qobject.h(115) : see declaration of 'QObject'
1>        This diagnostic occurred in the compiler generated function 'HItemBase::HItemBase(const HItemBase &)'

 

 

网上可以搜索到一条讨论:http://www.qtforum.org/article/23914/QObjectQObject--cannot-access-private-member-decla.html 原因是因为Qt基类对象QObject通过宏 Q_DISABLE_COPY disable了缺省的copy constructor和operator=。但是为什么要这样做让我很费解,论坛中的解决方案是自定定义copy constructor和operator=,这样确实可以解决问题,但是岂不是违背了DISABLE_COPY的初衷?

 

下面在看看Qt文档中对于该宏的说明:

 

Q_DISABLE_COPY ( Class )

Disables the use of copy constructors and assignment operators for the given Class.

Instances of subclasses of QObject should not be thought of as values that can be copied or assigned, but as unique identities. This means that when you create your own subclass of QObject (director or indirect), you should not give it a copy constructor or an assignment operator. However, it may not enough to simply omit them from your class, because, if you mistakenly write some code that requires a copy constructor or an assignment operator (it's easy to do), your compiler will thoughtfully create it for you. You must do more.

 

看来QObject对象及其派生类是不进行copy的,也就是说,QObject对象簇理论上都不应该被copy或者赋值。然后查看了一下QString,QLine,确实不是从QObject派生而来的。既然这样,那QObject的说明“The QObject class is the base class of all Qt objects.”就当做别的理解了。

 

因此我认为Qt的论坛Qtforum.org中的解答并不正确,正确的做法是:如果你的类需要copy或者被赋值,则不要让你的类从QObject派生。

 

欢迎拍砖:)