new & delete test

来源:互联网 发布:如何判断是否怀孕 知乎 编辑:程序博客网 时间:2024/05/17 22:07
#include <iostream>using namespace std;class A {    private:        int i;    public:        A(){            i = 0;            cout<<"A::A()"<<endl;        }        ~A(){            cout<<"A::~A(),i = "<< i <<endl;        }        void set(int i){            cout<<"set("<<i<<")"<<endl;            cout<<"this->i = "<<this->i<<endl;  //构造函数每次初始化 i = 0,即输出的this->i 为0;                                                // (每一个对象调用构造函数,i均被初始化);             this->i = i;            cout<<"this->i = "<<this->i<<endl;  //调用这个函数的那个对象的 i(即构造函数的i被赋值为                                                //函数set(i)的i;         }        void f(){            cout<<"hello"<<endl;        }}; int main(){    A *p = new A[10];   //申请对象空间,调用构造函数     cout<<"test beginning!"<<endl;     int i=0;    for(;i<10;i++){        p[i].set(i);    //调用函数A.set();     }    cout<<"test over"<<endl;     delete[] p;     //调用析构函数,之后对空间进行回收     return 0;}
原创粉丝点击