做了一小段测试程序,完全可以代表我项目中遇到的问题,下面的代码编译会出问题,这正是我想解决的问题,如果不用抽象类将例子中带“--”的行注释掉,将带“***”的行去掉注释,程序就可以正常运行。希望得到高手的指点。
抽象类:
#ifndef ABSTRACTA_H
#define ABSTRACTA_H
class AbstractA
{
public:
AbstractA();
virtual void Add(int a,int b)=0;
};
#endif // ABSTRACTA_H
#include "abstracta.h"
AbstractA::AbstractA(){}
继承类:
#ifndef SUBCLASSB_H
#define SUBCLASSB_H
#include <QtGui/QDialog>
#include "abstracta.h"
class SubclassB:public QDialog,public AbstractA
{
Q_OBJECT
public:
SubclassB();
virtual void Add(int a,int b);
signals:
void result(int z);
private:
int x;
};
#endif // SUBCLASSB_H
#include "subclassb.h"
SubclassB::SubclassB(){}
void SubclassB::Add(int a,int b)
{
x = a+b;
emit result(x);
}
客户程序:
#ifndef MYTEST_H
#define MYTEST_H
#include <QtGui>
#include "abstracta.h"
#include "subclassb.h"
class MyTest : public QDialog
{
Q_OBJECT
public:
MyTest(QWidget *parent = 0);
~MyTest();
private slots:
void ShowResult(int z);
void on_button_clicked();
private:
AbstractA *a; //---
//SubclassB *sub; ***
QPushButton *button;
};
#endif // MYTEST_H
#include "mytest.h"
MyTest::MyTest(QWidget *parent): QDialog(parent)
{
button = new QPushButton(this);
button->setText("push me");
connect(button,SIGNAL(clicked()),this,SLOT(on_button_clicked()));
}
MyTest::~MyTest(){}
void MyTest::ShowResult(int z)
{
button->setText(QString::number(z,10));
}
void MyTest::on_button_clicked()
{
a = new SubclassB(); //---
connect(a,SIGNAL(result(int)),this,SLOT(ShowResult(int)));//---
a->Add(10,20); //---
//sub = new SubclassB(); ***
//connect(sub,SIGNAL(result(int)),this,SLOT(ShowResult(int)));***
//sub->Add(10,20); ***
}
main函数:
#include <QtGui/QApplication>
#include "mytest.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MyTest w;
w.show();
return a.exec();
}
mytest.pro:
QT += core gui
TARGET = mytest
TEMPLATE = app
SOURCES += main.cpp\
mytest.cpp \
abstracta.cpp \
subclassb.cpp
HEADERS += mytest.h \
abstracta.h \
subclassb.h