#include<iostream.h>
using namespace std;
/**
* Cat *cat = new Cat; delete cat;
* 在释放内存之前将调用对象的析构函数,
*
* 迷途指针: delete释放指针,没有将其设置为空值
* */
class SimpleCat{
public:
SimpleCat();
~SimpleCat();
private:
int age;
}; //class 类终结要以 ; 结尾
SimpleCat::SimpleCat(){
cout<<"Constructor is called"<<endl;
age = 10;
}
SimpleCat::~SimpleCat(){
cout<<"DesConstructor is called"<<endl;
}
int main(){
cout<<"SimpleCat cat"<<endl;
SimpleCat cat; //被声明为 常规局部变量 因此在堆栈中创建,这种创建将导致构造函数被调用
cout<<"SimpleCat *pCat = new SimpleCat"<<endl;
SimpleCat *pCat = new SimpleCat; //使用了指针创建,在堆中创建,构造函数也将被调用
cout<<"delete pCat"<<endl;
delete pCat; // 将导致析构函数被调用
return 0;
//cat 不在其作用域中,因此其析构函数也将被调用
}
/**
* SimpleCat cat
Constructor is called
SimpleCat *pCat = new SimpleCat
Constructor is called
delete pCat
DesConstructor is called
DesConstructor is called
* */