C++的构造函数和析构函数
使用时机
构造函数调用在类对象创建时
析构函数调用在类对象销毁时
声明
构造函数声明必须跟类名一致,析构函数在构造函数前面加~
符号
例如
class Person {
public:string name;Person(string n) : name(n) {cout << "Constructor called for " << name << endl;}~Person() {cout << "Destructor called for " << name << endl;}
};
何时创建和销毁
类对象声明前面的{
表示该对象开始创建
与之对应的}
表示类对象销毁
例如
void example() {Person p("Bob"); // Constructor called here
} // Destructor called when p goes out of scope
如果函数内部还有{}
则对象的生存周期在最近的{}
内
例如
void example() {Person p("Bob"); // Constructor called here{Person p1("Alice");}Person p2("Jim"); // Constructor called here
} // Destructor called when p goes out of scope
p1
对象的析构函数调用会在p
函数之前