一、类的构造函数
1.基本概念
类的构造函数是类的一种特殊的成员函数,函数体可在类内或类外。
由用户创建,在对象创建时自动被调用。
可重载,即可定义不同参数个数和类型的构造函数。
构造函数的名称
与类的名称是完全相同的,一般声明为public,并且
不会返回任何类型,也不会返回 void。
构造函数可用于为某些成员变量设置初始值。
#include <iostream>
using namespace std;
class Line
{
public:
void setLength( double len );
double getLength( void );
Line(); // 这是构造函数
private:
double length;
};
// 成员函数定义,包括构造函数
Line::Line(void)
{
cout << "Object is being created" << endl;
}
void Line::setLength( double len )
{
length = len;
}
double Line::getLength( void )
{
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
2.带参数的构造函数
默认的构造函数没有任何参数,但如果需要,构造函数也可以带有参数。这样在创建对象时就会给对象赋初始值。
#include <iostream>
using namespace std;
class Line
{
public:
void setLength( double len );
double getLength( void );
Line(double len); // 这是带参数的构造函数
private:
double length;
};
// 成员函数定义,包括构造函数
Line::Line( double len)
{
cout << "Object is being created, length = " << len << endl;
length = len;
}
void Line::setLength( double len )
{
length = len;
}
double Line::getLength( void )
{
return length;
}
// 程序的主函数
int main( )
{
Line line(10.0);
// 获取默认设置的长度
cout << "Length of line : " << line.getLength() <<endl;
// 再次设置长度
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
return 0;
}
当上面的代码被编译和执行时,它会产生下列结果:
Object is being created, length = 10
Length of line : 10
Length of line : 6
3.使用初始化列表来初始化字段
Line::Line( double len): length(len)
{
cout << "Object is being created, length = " << len << endl;
}
上面的语法等同于如下语法:
Line::Line( double len)
{
length = len;
cout << "Object is being created, length = " << len << endl;
}
假设有一个类 C,具有多个字段 X、Y、Z 等需要进行初始化,形式如下:
C::C( double a, double b, double c): X(a), Y(b), Z(c)
{
....
}
二、析构函数
类的一种特殊的成员函数,会在每次删除所创建的对象时执行。
名称与类的名称是完全相同的,只是在前面加了个波浪号(~)作为前缀,它不会返回任何值,也不能带有任何参数。
一个类有且只有一个析构函数。若用户没有显式定义,系统会自动生成默认的析构函数。
当对象生命周期结束时,C++编译系统系统会自动调用析构函数,不能显式调用。
析构函数有助于在跳出程序(比如关闭文件、释放内存等)前释放资源。
#include<iostream>
using namespace std;
class A
{
public:
A()
{
cout<<"构造函数"<<endl;
}
~A()
{
cout<<"析构函数"<<endl;
}
};
int main()
{
A a;//a为A的对象
return 0;
}//在对象消失时,析构函数自动被调用,释放对象占用的空间
PS:函数名后的const声明,表示该成员函数不修改任何数据成员