对象实例化时候,会调用构造函数;而销毁对象时候,会调用析构函数
1、从栈中实例化对象
#includeusing namespace std; class Dog { public: Dog() { cout << "我是构造函数" << endl; }; ~Dog(); }; //或者写在外面 ( :: 是作用域运算符) Dog::~Dog() { cout << "我是析构函数" << endl; }; int main() { Dog dog1; return 0; }
2、从堆中实例化对象
#includeusing namespace std; class Dog { public: Dog() { cout << "我是构造函数" << endl; }; ~Dog(); }; //或者写在外面 ( :: 是作用域运算符) Dog::~Dog() { cout << "我是析构函数" << endl; }; int main() { Dog *dog2 = new Dog; return 0; }
运行:
发现,析构函数没有执行;
这是因为:这是因为从堆中实例化对象,需要用到delete关键字来删除;
#includeusing namespace std; class Dog { public: Dog() { cout << "我是构造函数" << endl; }; ~Dog(); }; //或者写在外面 ( :: 是作用域运算符) Dog::~Dog() { cout << "我是析构函数" << endl; }; int main() { Dog *dog2 = new Dog; delete dog2; return 0; }



