首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

new delete 例证

2014-01-12 
new delete 例子#include iostreamusing namespace stdint main ( ){//基本数据类型int *i new int/

new delete 例子

#include <iostream>using namespace std;int main ( ){    //基本数据类型    int *i = new int;              //没有初始值    int *j = new int(100);         //初始值为100    float *f = new float(3.1415f); //初始值为3.14159    cout <<"  i = " << *i << endl;    cout <<"  j = " << *j << endl;    cout <<"  f = " << *f << endl;    //数组    int *iArr = new int[3];    for (int i=0; i<3; i++) {        iArr[i] = (i+1)*10;        cout << i << ": " << iArr[i] << endl;    }    //释放内存    delete i;    delete j;    delete f;    delete []iArr;    //注意数组的删除方法    return 0;}

?

#include <iostream>#include <new>using namespace std;int main ( ){    //判断指针是否为NULL    double *arr = new double[100000];    if (!arr) {        cout <<"内存分配出错!" << endl;        return 1;    }    delete []arr;    //例外出错处理    try {        double *p = new double[100000];        delete []p;    } catch (bad_alloc xa) {        cout <<"内存分配出错!" << endl;        return 1;    }    //强制例外时不抛出错误,这时必须要判断指针    double *ptr = new(nothrow) double[100000];    if (!ptr) {        cout <<"内存分配出错!" << endl;        return 1;    }    delete []ptr;    cout <<"内存分配成功!" << endl;    return 0;}

?

#include <iostream>using namespace std;class classA {    int x;public:    classA(int x) { this->x = x; }    int getX() { return x; }};int main ( ){    classA *p = new classA(200);    //调用构造函数    if (!p) {        cout <<"内存分配出错!" << endl;        return 1;    }    cout <<"x = " << p->getX() << endl;    delete p;    //调用析构函数    return 0;}

?

?

?

?

热点排行