多重继承中的信号与槽

最近在公司项目中开发串口,因为历史原因串口要包装一下,且包装类需要继承自一个纯C++类。
QSerialPort可以使用slot function来获取从串口读到的数据,以及写入串口的bytes个数。因此就给自己的类加了对应的槽函数。代码示例如下:

#include 
class CBase
{
public:
  CBase();
  ~CBase();
};

class CDerive:public CBase,public QObject
{
  Q_OBJECT
public:
  CDerive();
  ~CDerive();
public slots:
   void slot1();
  signals:
};

当然了,这段代码压根不能编译,错误如下:

debug/moc_CObejctTest.cpp:77:8: error: ‘staticMetaObject’ is not a member of ‘CBase’
{ &CBase::staticMetaObject, qt_meta_stringdata_CDerive.data,
^
debug/moc_CObejctTest.cpp: In member function ‘virtual void* CDerive::qt_metacast(const char*)’:
debug/moc_CObejctTest.cpp:94:12: error: ‘qt_metacast’ is not a member of ‘CBase’
return CBase::qt_metacast(_clname);
^
debug/moc_CObejctTest.cpp: In member function ‘virtual int CDerive::qt_metacall(QMetaObject::Call, int, void**)’:
debug/moc_CObejctTest.cpp:99:11: error: ‘qt_metacall’ is not a member of ‘CBase’
_id = CBase::qt_metacall(_c, _id, _a);
^
debug/moc_CObejctTest.cpp: In member function ‘virtual void* CDerive::qt_metacast(const char*)’:
debug/moc_CObejctTest.cpp:95:1: warning: control reaches end of non-void function [-Wreturn-type]
}
^
Makefile.Debug:316: recipe for target ‘debug/moc_CObejctTest.o’ failed
mingw32-make[1]: * [debug/moc_CObejctTest.o] Error 1

去查看Qt生成的moc文件:

const QMetaObject CDerive::staticMetaObject = 
{
  { 
    &CBase::staticMetaObject, //-----------------
    qt_meta_stringdata_CDerive.data,
    qt_meta_data_CDerive, 
    qt_static_metacall, 
    Q_NULLPTR, 
  Q_NULLPTR
  }
};

注意其中有注释的一行,CBase并不是继承自QObject,所以也就不存在staticMetaObject类。 可是CDerive明明也有继承自QObject类,为啥生成的moc认到了CBase了呢
然后想到把QObject放到第一个父类的位置。如下:
class CDerive:public QObject,public CBase
这样就可以编译通过了。生成的moc如下:

const QMetaObject CDerive::staticMetaObject = {
 { &QObject::staticMetaObject, qt_meta_stringdata_CDerive.data,
 qt_meta_data_CDerive, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};

这就尴尬了。 难道moc只认继承列表中第一个位置的?
这个问题有空要查一下。。。。O(∩_∩)O哈哈哈~

你可能感兴趣的:(Qt)