在C++的构造函数的调用虚函数,则是当前类的虚函数,而不是子类派生的那一个。
Qt 的 connect 函数在构造函数中也要谨慎连接虚函数。
比如有这么一个demo:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
   | #include <QApplication> #include <QObject> #include <QDebug>
  class Test : public QObject {     Q_OBJECT public:     void onEmit() {         emit test();     } signals:     void test(); };
  class Base : public QObject {     Q_OBJECT public:     Base(Test *p) {         this->p = p;         connect(p,SIGNAL(test()), this, SLOT(onTest()));     }     void testConnect() {          }
  private slots:     void onTest() {         qDebug() << "This is Base's test";     } private:     Test *p; };
  class Child : public Base {     Q_OBJECT public:     Child(Test *p) : Base(p)     {     } private slots:     void onTest() {         qDebug() << "This is Child's test";     } }; int main(int argc, char **argv) {     Test t;     Base *b = new Child(&t);     b->testConnect();     t.onEmit();     return 0; }
   | 
 
在基类构造函数的时候建立connect机制,这个时候connect中的this虽然地址和Child是一致,但如果用typeid可以发现connect的this的类型是Base,moc文件会去选择用Base::metaObject,而不是去用Child::metaObject去和Test的信号关联。
这个时候会出现什么问题?没错,基类指针指向子类类型,在你槽函数没进行虚函数的情况下,你虽然以为connect会去调用你子类的槽函数,但实际情况是,基类指针仍旧去调用基类函数。所以,在构造函数中写connect的务必把槽函数设置成虚函数。
解决方法就是不要在构造函数中调用,在创建之后再在外面的作用域调用它的connect。
参考:https://www.cnblogs.com/rickyk/p/3835695.html