2012-11-30 37 views

回答

5

A的构造函数时自动调用你构建一个B.

如果您需要将参数传递到A的构造函数有它正常工作,明确要求其在B的构造函数:

B::B() 
:A(Blah) 
{ 
} 

这将是共同的,当A是的QObject,并且希望拥有的东西正确发生,你“会通过在B的构造函数父指针并传递到A的:

B::B(QObject* parent_) 
:A(parent_) 
{ 
} 

这是无关Qt和是一个纯粹的C++概念。

2

您将有文件:

A.H

#ifndef A_H 
#define A_H 

class A 
{ 
public: 
    A(); 
}; 

#endif // A_H 

a.cpp

#include "a.h" 
#include <QDebug> 

A::A() 
{ 
    qDebug() << "A()"; 
} 

b.h

#ifndef B_H 
#define B_H 

#include "a.h" 

class B : public A 
{ 
public: 
    B(); 
}; 

#endif // B_H 

b.cpp

#include "b.h" 
#include <QDebug> 

B::B() : A() 
{ 
    qDebug() << "B()"; 
} 

main.cpp中

#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() 
B() 
相关问题