类的构造方法,私有属性赋值、取值,析构函数作用以及执行顺序
1.创建一个类 里面有对应的函数
class Line
{
public:
void setLenth(double len);
double getLenth(void);
//类的构造函数是类的一种特殊的成员函数,它会在每次创建类的新对象时执行。
Line(); //无参构造
Line(double len); //有参构造 创建对象时就会给对象赋初始值
//类的析构函数是类的一种特殊的成员函数,它会在每次删除所创建的对象时执行。
~Line(); //析构函数有助于在跳出程序(比如关闭文件、释放内存等)前释放资源。
void plant(); //测试展示
//属性
private:
double lenth;
};
2.对应的源文件函数实现
void Line::setLenth(double len)
{
this->lenth = len;
}
double Line::getLenth()
{
return this->lenth;
}
Line::Line()
{
qDebug() << "object is beging creat1" ;
}
Line::Line(double len)
{
this->lenth = len;
qDebug() << "object is beging creat2 length = " << len;
}
Line::~Line()
{
qDebug() << "object is beging delete" << this->getLenth() ;
}
void Line::plant()
{
Line line;
line.setLenth(10.0);
qDebug() << "line's lenth is " << line.getLenth();
Line line2(5.0);
qDebug() << "line2's lenth is " << line2.getLenth();
}
3.在main源文件导入这个类的头文件 并且使用
#include "mainwindow.h"
#include "line.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
Line line;
line.plant();
w.show();
return a.exec();
}
4.运行后看一下打印结果
关闭窗口后,还会来一句:
object is beging delete 7.09327e+141
5.顺序:
可以看得出
1.main里面的构造函数
2.调用了plant() 后
3.第一个line的构造函数
4.打印语句
5.第二个line的构造函数
6.打印语句
7.第二个line的析构函数
8.第一个line的析构函数
关闭页面后
9.main里面line的析构函数
谢谢~~