C++ 类构造函数 & 析构函数
C++ 类 & 对象
类的构造函数
类的构造函数是类的一种特殊的成员函数,它会在每次创建类的新对象时自动执行。
构造函数的名称与类的名称完全相同,且没有返回类型(连 void 也不能有)。构造函数通常用于为成员变量设置初始值。
若未显式定义构造函数,编译器会自动生成一个不执行任何操作的默认构造函数。
下面的实例有助于更好地理解构造函数的概念:
实例
#include <iostream>
using namespace std;
class Line
{
public:
Line();
void setLength(double len);
double getLength() const;
private:
double length;
};
Line::Line()
{
cout << "Object is being created" << endl;
length = 0.0;
}
void Line::setLength(double len)
{
length = len;
}
double Line::getLength() const
{
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
带参数的构造函数
默认的构造函数没有任何参数,但如果需要,构造函数也可以带有参数。这样在创建对象时就会给对象赋初始值,无需再单独调用 set 函数,如下面的例子所示:
实例
#include <iostream>
using namespace std;
class Line
{
public:
Line(double len);
void setLength(double len);
double getLength() const;
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() const
{
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
使用初始化列表来初始化字段
C++ 推荐使用成员初始化列表来初始化成员变量。它的语法是在构造函数参数列表后加冒号(:),然后写 成员变量名(初始值)。
以下示例中,: length(len) 的含义是:用传入的参数 len 直接初始化成员变量 length。注意 cout 打印的是成员变量 length,而非参数 len,这样可以直观地验证成员变量已被正确赋值:
Line::Line(double len) : length(len)
{
cout << "Object is being created, length = " << length << endl;
}
上面的语法等同于如下在函数体内赋值的写法,两者输出结果完全相同:
Line::Line(double len)
{
length = len;
cout << "Object is being created, length = " << length << endl;
}
两种写法的区别在于:初始化列表在进入函数体之前就完成了成员变量的初始化,而函数体内赋值是先默认构造、再赋值,多了一步。对于 const 成员、引用成员以及没有默认构造函数的对象成员来说,初始化列表是唯一的初始化方式。
假设有一个类 C,具有多个字段 X、Y、Z 等需要进行初始化,只需在不同字段之间用逗号分隔,如下所示:
C::C(double a, double b, double c) : X(a), Y(b), Z(c)
{
}
注意:初始化列表中各成员的初始化顺序由它们在类中的声明顺序决定,而非书写顺序,建议保持一致以避免混淆。
类的析构函数
类的析构函数是类的一种特殊的成员函数,在对象的生命周期结束时(离开作用域或被 delete)自动执行,用于释放对象占用的资源(如动态内存、文件句柄等)。
析构函数的名称与类的名称完全相同,只是在前面加了个波浪号(~)作为前缀。它不会返回任何值,也不能带有任何参数,每个类只能有一个析构函数。
下面的实例有助于更好地理解析构函数的概念:
实例
#include <iostream>
using namespace std;
class Line
{
public:
Line();
~Line();
void setLength(double len);
double getLength() const;
private:
double length;
};
Line::Line()
{
cout << "Object is being created" << endl;
length = 0.0;
}
Line::~Line()
{
cout << "Object is being deleted" << endl;
}
void Line::setLength(double len)
{
length = len;
}
double Line::getLength() const
{
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
C++ 类 & 对象