new/delete 的使用要点

运算符 new 使用起来要比函数 malloc 简单得多,例如: int *p1 = (int *)malloc(sizeof(int) * length); int *p2 = new int[length]; 这是因为 new 内置了 sizeof、类型转换和类型安全检查功能。

对于非内部数据类型 的对象而言,new 在创建动态对象的同时完成了初始化工作。如果对象有多个构造函数, 那么 new 的语句也可以有多种形式。

 1 #include <iostream>
 2 
 3 /* run this program using the console pauser or add your own getch, system("pause") or input loop */
 4 using namespace std;
 5 int main(int argc, char** argv) {
 6     //声明数组、变量和指针变量
 7     int a[]={1,2,3,4,5,6};
 8     int *ip1,*ip2;
 9 
10     //测试指针的赋值运算
11     ip1=a;
12     ip2=ip1;   
13     cout<<"*ip1="<<(*ip1)<<endl;
14     cout<<"*ip2="<<(*ip2)<<endl;
15 
16     //测试指针的自增自减运算和组合运算
17     ip1++;  
18     ip2+=4; 
19     cout<<"*ip1="<<(*ip1)<<endl;
20     cout<<"*ip2="<<(*ip2)<<endl;
21     
22     //测试指针变量之间的关系运算
23     int n=ip2>ip1;
24     cout<<"ip2>ip1="<<n<<endl;
25     cout<<"ip2!=NULL="<<(ip2!=NULL)<<endl;
26 
27     //指针变量之间的减法
28     n=ip2-ip1;
29     cout<<"ip2-ip1="<<n<<endl;
30     return 0;
31 }

 

posted @ 2018-08-02 12:35  borter  阅读(145)  评论(0编辑  收藏  举报