Inheritance 如何在Qt Creator中使用超类构造函数?
您可能知道,Qt Creator中的类作为class.h和class.cpp文件是项目的一部分。假设我们有两个类A(A.h,A.cpp)和B(B.h,B.cpp),B继承了A。在使用B的构造函数时,如何使用A的构造函数?您将拥有以下文件: a.h:Inheritance 如何在Qt Creator中使用超类构造函数?,inheritance,constructor,qt-creator,qt5,Inheritance,Constructor,Qt Creator,Qt5,您可能知道,Qt Creator中的类作为class.h和class.cpp文件是项目的一部分。假设我们有两个类A(A.h,A.cpp)和B(B.h,B.cpp),B继承了A。在使用B的构造函数时,如何使用A的构造函数?您将拥有以下文件: a.h: #ifndef A_H #define A_H class A { public: A(); }; #endif // A_H #include "a.h" #include <QDebug> A::A() { q
#ifndef A_H
#define A_H
class A
{
public:
A();
};
#endif // A_H
#include "a.h"
#include <QDebug>
A::A()
{
qDebug() << "A()";
}
#ifndef B_H
#define B_H
#include "a.h"
class B : public A
{
public:
B();
};
#endif // B_H
#include "b.h"
#include <QDebug>
B::B() : A()
{
qDebug() << "B()";
}
#include <QCoreApplication>
#include <QDebug>
#include "a.h"
#include "b.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
B ob;
return a.exec();
}
a.cpp:
#ifndef A_H
#define A_H
class A
{
public:
A();
};
#endif // A_H
#include "a.h"
#include <QDebug>
A::A()
{
qDebug() << "A()";
}
#ifndef B_H
#define B_H
#include "a.h"
class B : public A
{
public:
B();
};
#endif // B_H
#include "b.h"
#include <QDebug>
B::B() : A()
{
qDebug() << "B()";
}
#include <QCoreApplication>
#include <QDebug>
#include "a.h"
#include "b.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
B ob;
return a.exec();
}
b.cpp:
#ifndef A_H
#define A_H
class A
{
public:
A();
};
#endif // A_H
#include "a.h"
#include <QDebug>
A::A()
{
qDebug() << "A()";
}
#ifndef B_H
#define B_H
#include "a.h"
class B : public A
{
public:
B();
};
#endif // B_H
#include "b.h"
#include <QDebug>
B::B() : A()
{
qDebug() << "B()";
}
#include <QCoreApplication>
#include <QDebug>
#include "a.h"
#include "b.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
B ob;
return a.exec();
}
构造B时,会自动调用A的构造函数 如果需要将参数传递给A的构造函数以使其正常工作,请在B的构造函数中显式调用它:
B::B()
:A(Blah)
{
}
如果A是QObject,并且您希望正确发生所有权内容,那么这将很常见,您将在B的构造函数中传入父指针,并将其传递到A的:
B::B(QObject* parent_)
:A(parent_)
{
}
<>这与QT无关,是一个纯粹的C++概念。