在C++中还有我们之前没有接触过的函数和方法,那就是类的构造函数和析构函数,其实说上去这两个函数也很容易理解,一个是在类创建时调用,另一个是在类销毁或程序结束时调用的函数。
一、类的构造函数
1.一般构造函数:
类的构造函数是类的一种特殊的成员函数,它会在每次创建类的新对象时执行。
构造函数的名称与类的名称是完全相同的,并且不会返回任何类型,也不会返回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(void) {
Line line;
// 设置长度
line.setLength(6.0);
cout << "Length of line : " << line.getLength() << endl;
return 0;
}
这里可能就出现了很多不理解的因素,比如::
之类的,其实它是范围解析运算符
,说白了也没啥要理解的东西,还有就是带参数的构造函数。
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(void) {
Line line(10.0);
// 获取默认设置的长度
cout << "Length of line : " << line.getLength() <<endl;
// 再次设置长度
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
return 0;
}
如果还嫌麻烦的话,我们也可以使用初始化列表来初始化字段。
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::C(double a, double b, double c): X(a), Y(b), Z(c) {
....
}
二、类的析构函数
类的析构函数就和构造函数类似,不过他只是在类销毁时才调用的,并且该方法也是和类名相同的,不过需要在前面加一个~
用以区分两种方法。
#include <iostream>
using namespace std;
class Line {
public:
void setLength(double len);
double getLength(void);
Line(); // 这是构造函数声明
~Line(); // 这是析构函数声明
private:
double length;
};
// 成员函数定义,包括构造函数
Line::Line(void) {
cout << "Object is being created" << endl;
}
Line::~Line(void) {
cout << "Object is being deleted" << endl;
}
void Line::setLength(double len) {
length = len;
}
double Line::getLength(void) {
return length;
}
// 程序的主函数
int main(void) {
Line line;
// 设置长度
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
return 0;
}