码迷,mamicode.com
首页 > 其他好文 > 详细

new/delete 的使用要点

时间:2018-08-02 12:53:12      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:安全   ogr   you   初始   return   str   new   getch   oop   

运算符 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 }

 

new/delete 的使用要点

标签:安全   ogr   you   初始   return   str   new   getch   oop   

原文地址:https://www.cnblogs.com/borter/p/9406479.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!