zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    React.js自学第一天
    优化的34条定律
    JS 打字机效果
    css3 翻书效果
    对象操作
    表单提交验证
    封装cookie组件
    iOS中为网站添加图标到主屏幕
    教你从Win8换回Win7
    关于VB中Print函数在数组中换行的理解
  • 原文地址:https://www.cnblogs.com/borter/p/9406479.html
Copyright © 2011-2022 走看看