码迷,mamicode.com
首页 > 编程语言 > 详细

C++ new 和 delete 详细解析

时间:2015-05-05 19:15:50      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:

C++中的new 和delete 是操作符,new 分配对象时候会自动调用构造函数,delete对象时候,会自动调用析构函数,而C语言中 malloc() 和 free() 是函数。 理论上malloc free 和 new 、delete 可以混搭用,但是最好不要这样用,也不能保证程序正确运行。

 

C++中new 和delete的语法格式如下:

 

技术分享

 

#include "stdlib.h"
#include "stdio.h"
#include "string.h"
#include <iostream>
using namespace std;

//new 和delete是操作符
//malloc() 和free() 是函数
//new 在堆上分配基础类型、分配数组类型、分配对象

int main01() {
    
    //new基础类型
    int* p = (int*)malloc(sizeof(int));
    free(p);

    int* p2 = new int;
    *p2 = 101;
    printf("*p2:%d \n", *p2);
    delete p2;
    
    //开辟一个存放整数的空间,并指定该整数的初值为100
    int* p3 = new int(100);


    system("pause");
    return 0;
}

class Test {
public:
    Test(int mya, int myb) {
        cout << "构造函数,我被调用了" <<endl;
        a = mya;
        b = myb;
    } 
    ~Test() {
        cout << "析构函数,我被调用了" << endl;
    }
    int getA(){
        return a;
    }
protected:
private:
    int a;
    int b;

};
int main() {

    //new数组
    int* p1 = (int*)malloc(10*sizeof(int)); //int a[10]
    p1[0] = 1 ;
    free(p1);

    int* p2 = new int[10];
    p2[0] = 1;
    p2[1] = 2;
    delete [] p2;

    //new对象 new操作符也会自动的调用这个类的构造函数
    //delete自动的调用这个类的析构函数,说明程序员可以
    //手动控制类对象的生命周期
    Test* p3 = new Test(1,2);

    cout << p3->getA() << endl;
    delete p3;

    system("pause");
    return 0;
}

C++ new 和 delete 详细解析

标签:

原文地址:http://www.cnblogs.com/manxinhuanxizhu/p/4479701.html

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