[C++基础]008_类的构造函数和析构函数
2012-10-09 00:47
302 查看
#include<iostream> using namespace std; class Human{ public: Human(){ cout<<"constrct"<<endl; } ~Human(){ cout<<"destruct"<<endl; } private: int age; }; int main(){ Human human; Human *humanPtr; humanPtr = new Human(); delete humanPtr; system("pause"); return 0; }
上面的代码输出 什么呢?如下:
constrct constrct destruct 请按任意键继续. . .
为毛只有一个destruct呢?难道第一个对象不析构吗?不是的!在main函数执行return的时候,析构函数就会被调用了.
不信,看如下代码:
#include<iostream> using namespace std; class Human{ public: Human(){ cout<<"constrct"<<endl; } ~Human(){ cout<<"destruct"<<endl; } private: int age; }; int test(){ Human human; return 0; } int main(){ test(); Human *humanPtr; humanPtr = new Human(); delete humanPtr; system("pause"); return 0; }
输出如下:
constrct destruct constrct destruct 请按任意键继续. . .
看到了吧,在调用test()之后,析构函数被调用了.
相关文章推荐
- [C++基础]008_类的构造函数和析构函数
- c++基础语法 构造函数 析构函数 类的组合
- C++语言基础 例程 调用构造函数和析构函数的顺序
- C++学习基础十——子类构造函数与析构函数的执行
- C++语法基础--派生类的构造函数,赋值操作符,析构函数,虚析构函数
- C++基础:派生类的构造函数与析构函数调用顺序
- C++【构造函数与析构函数基础知识以及构造析构顺序】
- c++基础语法:构造函数与析构函数
- C++语言基础(4)-构造函数和析构函数
- C++基础(一)构造函数、析构函数、拷贝构造函数
- C++语言基础 例程 派生类的构造函数和析构函数
- C++基础-构造函数/析构函数/拷贝构造
- C++基础4:构造函数、析构函数、拷贝构造函数、静态成员函数
- C++基础学习9:构造函数和析构函数
- C++基础---构造函数与析构函数
- C++基础(九)继承与派生——派生类成员的构造函数和析构函数
- C++基础--构造函数与析构函数
- c++之基础知识(1)定义类的对象;析构函数和构造函数常用模板
- C++基础知识---构造函数 & 析构函数 & 虚拟析构函数
- c++基础学习7-c++构造函数和析构函数