qt中會不小心遇到error: undefined reference to `vtable for ....'原來是是子類的一個虛函數聲明了,但是,在.cpp中沒有定義 實現代碼。
比如在.h中把~hellodialog()屏蔽掉后;
:
1 class hellodialog : public QDialog 2 { 3 Q_OBJECT 4 public: 5 explicit hellodialog(QWidget*parent = 0); 6 // ~hellodialog(); 7 8 signals: 9 10 public slots: 11 12 private: 13 // Ui::hellodialog *ui; 14 };
而在.cpp中把~hellodialog()的定義也去掉
1 hellodialog::hellodialog(QWidget *parent) : QDialog(parent) 2 { 3 //ui = new Ui::hellodialog; 4 //ui->setupUi(this); 5 } 6 7 //hellodialog::~hellodialog() 8 //{ 9 // delete ui; 10 //}
就不會報錯了。當我們把這兩個屏蔽都去掉后,就會報錯。
在其他博客上看到比較好的知識點,粘貼過來:
比如:
class QParent
{
public:
QParent();
virtual ~QParent();
...//其它代碼
};
class QChild:public QParent
{
public:
QChild();
~QChild();
...//其它代碼
};
顯然類QChild的析構函數~QChild()是一個虛函數,必須得定義它。所以在QChild的實現.cpp文件中
應該添加該函數的實現部分,如下
QChild::~QChild()
{
...//實現代碼
}
如果你認為QChild不需要釋放資源,不需要添加實現代碼,可以把類聲明改一下即可,如下
class QChild:public QParent
{
public:
QChild();
~QChild(){};
...//其它代碼
};
紅色部分為添加部分,如果不添加也不在實現.cpp文件添加該虛函數的實現就會出“undefined reference to `vtable for QChild”的錯誤