构造函数
它是一种机制,他能保证我们的对象只要创建出来就可以被初始化。
构造函数没有返回类型,他在类对象被创建的时候自动被调用。
析构函数
析构函数:在类对象结束之前会被调用 ,他是不带参数的。
constructoranddestructoe.h
#ifndef CONSTRUCTORANDDESTRUCTOR_H
#define CONSTRUCTORANDDESTRUCTOR_H
#include <QWidget>
class ConstructorAndDestructor : public QWidget
{
Q_OBJECT
public:
ConstructorAndDestructor(QWidget *parent = 0); //构造函数
~ConstructorAndDestructor(); //析构函数
int i;
void f();
};
#endif // CONSTRUCTORANDDESTRUCTOR_H
tree.h
#ifndef TREE_H
#define TREE_H
class Tree
{
int hight;
public:
Tree(int initialhight); //构造函数带参数
~Tree();
void grow (int year);
void printsize();
};
#endif // TREE_H
constructoranddestructoe.cpp
#include "constructoranddestructor.h"
#include <QDebug>
ConstructorAndDestructor::ConstructorAndDestructor(QWidget *parent)//构造函数
: QWidget(parent)
{
qDebug() << "构造函数被调用"<<endl; //应用输出 NO.2
ConstructorAndDestructor::i = 1;
qDebug() << "ConstructorAndDestructor="+ QString::number(ConstructorAndDestructor::i) <<endl; // 应用输出 NO.3
}
ConstructorAndDestructor::~ConstructorAndDestructor() //析构函数
{
qDebug() << "析构函数被调用" <<endl; //应用输出 NO.14
}
void ConstructorAndDestructor::f()
{
qDebug() << "f()=" + QString::number(ConstructorAndDestructor::i) << endl; //应用输出 NO.4
ConstructorAndDestructor::i=10;
qDebug() << "f()=" + QString::number(ConstructorAndDestructor::i) << endl; //应用输出 NO.5
}
tree.cpp
#include "tree.h"
#include <QDebug>
Tree::Tree(int initialhight)
{
hight =initialhight;
qDebug() << "在构造函数里面"<< endl;//应用输出 NO.7
}
Tree::~Tree(){
qDebug() << "在析构函数里面"<< endl; //应用输出 NO.11
printsize();
}
void Tree::grow(int year )
{
hight +=year;
}
void Tree::printsize(){
qDebug() << "TREE HIGHT IS" + QString::number(hight) <<endl; //应用输出 NO.9 应用输出 NO.12
}
main.cpp
#include "constructoranddestructor.h"
#include <QApplication>
#include <QDebug>
#include "tree.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
qDebug() << "启动" <<endl; //启动构造函数 应用输出 NO.1
ConstructorAndDestructor w; //调用构造函数
w.f();
w.show();
//tree 类(析构函数带参数)的使用
qDebug() << "before openning brace "<< endl;//应用输出 NO.6
{
Tree t(12); //把inITialhight =12; 进入tree构造函数
qDebug() << "after tree creation" << endl; //应用输出 NO.8
t.printsize();
t.grow(4);
qDebug() << "before closing brace"<<endl; //应用输出 NO.10
// Tree m(); //如果不带参,能进入构造函数吗? 发现不能
}//调用tree析构函数
qDebug() << "after closing brace"<<endl; //应用输出 NO.13
return a.exec();
}