#includeusing namespace std; class CreateAndDestroy{ public: CreateAndDestroy(int n) { no=n; cout<<"Object "< cout<<"Object "< CreateAndDestroy*ptr; CreateAndDestroy two(2);// 定义局部动态对象 two { CreateAndDestroy three(3);// 定义局部动态对象 three ptr=new CreateAndDestroy(4); // 动态创建对象 static CreateAndDestroy five(5); // 定义局部静态对象 five } delete ptr;// 释放动态创建的对象 return 0; }
输出结果:
输出结果(省去末尾回车):
Object 1created!
Object 2created!
Object 3created!
Object 4created!
Object 5created!
Object 3destructed!
Object 4destructed!
Object 2destructed!
Object 5destructed!
Object 1destructed!
结论:
先释放main程序return前的对象,依次即3,4
之后局部动态(2)->局部静态(5)->全局变量(1)
hello.h
#ifndef UNTITLED_HELLO_H #define UNTITLED_HELLO_H #include#include using namespace std; class hello { public: hello(int n); ~hello(); int no; }; #endif //UNTITLED_HELLO_H }
hello.cpp
#include "hello.h"
hello::hello(int n) {
no=n; cout<<"hello "<
}
world.h
#ifndef UNTITLED_WORLD_H
#define UNTITLED_WORLD_H
#include "hello.h"
using namespace std;
class world {
public:
world(int n);
~world();
hello* hell;
int no;
};
#endif //UNTITLED_WORLD_H
world.cpp
#include "world.h"
world::world(int n) {
no=n; cout<<"world "<
cout<<"world "<
main.cpp
#include
#include
using namespace std;
#include "world.h"
int main(){
world* s= new world(1);
delete s;
int mm=1;
}



