C++程序设计(构造与析构)
initialization with the constructor
- if a class has a constructor,the compiler automatically calls that constructor at the point an object is created,before client programmers can get their hands on the object.
- the name of the constructor is the same as the name of the class
构造函数的结构
#include<iostream>
using namespace std;
class A{
public:
A(){
cout<<"a had created"<<endl;
}
};
int main(){
A a;
return 0;
}
result
a had created
The destructor(析构函数)
- The destructor can clean up one object when something happens
- The destructor is named after the name of the class with a leading tilde(~).The destructor never has any arguments(参数)
#include<iostream>
using namespace std;
class A{
public:
~A(){
cout<<"a had been cleaned up"<<endl;
}
};
int main(){
A a;
return 0;
}
result
a had been cleaned up