new delete 例子
#include
<iostream>using namespace
std;int
main ( ){ //基本数据类型int
*i =new int
; //没有初始值int
*j =new int
(100); //初始值为100float
*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 ( ){ //判断指针是否为NULLdouble
*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;}
?
?
?
?