构造函数&析构函数
类的构造函数——创建类的对象
类的构造函数是一个特殊的成员函数,它会在每次创建类的新对象时执行。
构造函数的名称与类的名称是完全相同的,并且不会返回任何类型,也不会返回 void。
test
#include <iostream>
using namespace std;
class Line
{
public:
Line(); // 这是构造函数
void setLength(double len);
double getLength();
private:
double length;
};
// Line类的构造函数
Line::Line()
{
cout << "Object is being created" << endl;
}
void Line::setLength(double len){length = len;}
double Line::getLength(){return length;}
// 程序的主函数
int main( )
{
Line line;//类 对象 运行构造函数并输出
// 设置长度
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
return 0;
}
输出:
Object is being created
Length of line : 6
类的析构函数——删除所创建类的对象
类的析构函数是类的一种特殊的成员函数,它会在每次删除所创建的对象时执行。
析构函数的名称与类的名称是完全相同的,只是在前面加了个波浪号(~)作为前缀,它不会返回任何值,也不能带有任何参数。
析构函数有助于在跳出程序(比如关闭文件、释放内存等)前释放资源。
Qt中只有主函数里面有的,其他自定义的类里都默认不添加,因为Qt的析构函数是为了删除ui界面
(选择mainwindow类,就只有mainwindow类中有)
MainWindow::~MainWindow()
{
delete ui;
}
test
第二个例子中仅仅是多了一个析构函数,其他都一样
#include <iostream>
using namespace std;
class Line
{
public:
Line(); // 这是构造函数声明
~Line(); // 这是析构函数声明
void setLength( double len );
double getLength( );
private:
double length;
};
// 成员函数定义,包括构造函数和析构函数
Line::Line()
{
cout << "Object is being created" << endl;
}
//定义析构函数
Line::~Line()
{
cout << "Object is being deleted" << endl;
}
void Line::setLength(double len){
length = len;
}
double Line::getLength(){
return length;
}
// 程序的主函数
int main( )
{
Line line;
// 设置长度
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
return 0;
}
输出:
Object is being created
Length of line : 6
Object is being deleted