第十五课:类的构造函数和析构函数
学习目标:
- 了解构造函数和析构函数的概念及其作用。
- 学习如何定义和使用构造函数和析构函数。
- 掌握构造函数的重载。
学习内容:
-
构造函数和析构函数的概念:
- 构造函数: 类的特殊成员函数,会在创建对象时自动调用,用于初始化对象的成员变量。
- 析构函数: 类的另一个特殊成员函数,会在对象生命周期结束时自动调用,用于进行清理工作,如释放资源。
-
定义构造函数和析构函数:
- 代码示例:
#include <iostream> using namespace std; class Box { public: double length; double breadth; double height; // 构造函数声明 Box(double l, double b, double h) { cout << "Box 被创建" << endl; length = l; breadth = b; height = h; } // 析构函数声明 ~Box() { cout << "Box 被销毁" << endl; } double getVolume() { return length * breadth * height; } }; int main() { Box Box1(6.0, 7.0, 5.0); // 创建对象时自动调用构造函数 cout << "Box1 的体积:" << Box1.getVolume() << endl; return 0; }
- 预计输出效果:
Box 被创建 Box1 的体积:210 Box 被销毁
- 使用场景: 构造函数用于任何需要初始化对象状态的场景,析构函数则用于清理在对象生命周期中分配的资源,如动态分配的内存、文件句柄等。
- 代码示例:
练习题: 编写一个类Student
,它有两个私有成员变量name
和age
,编写一个构造函数来初始化这些变量,并编写一个析构函数打印一条消息说明对象被销毁。另外,添加一个成员函数displayInfo()
来输出学生信息。在main
函数中创建一个Student
对象并演示其构造和析构过程。
答案:
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
string name;
int age;
public:
// 构造函数
Student(string n, int a) : name(n), age(a) {
cout << "Student " << name << " 被创建" << endl;
}
// 析构函数
~Student() {
cout << "Student " << name << " 被销毁" << endl;
}
// 显示学生信息
void displayInfo() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
int main() {
Student student1("Alice", 20);
student1.displayInfo();
return 0; // student1 被销毁
}
预计输出效果:
Student Alice 被创建
Name: Alice, Age: 20
Student Alice 被销毁