构造函数在对象创建时自动调用,用于初始化。与类同名,无返回类型。C++提供:默认构造、参数构造、拷贝构造。
初始化列表(推荐):Student():name("未知"),age(0){} 比函数体内赋值更高效。
Student():name("未知"),age(0){}
析构函数在对象销毁时自动调用:~ClassName(){ ... } 用于清理资源。
~ClassName(){ ... }
拷贝构造:Student(const Student& other):name(other.name),age(other.age){}
Student(const Student& other):name(other.name),age(other.age){}