6、面向对象-动态对象建立(堆类型对象)

一、malloc(库函数)在C++中的作用

单纯的申请一块内存,不执行对象的建立(没有调用构造函数

#include <iostream>
#include <cstdlib>

using namespace std;

class Test
{
public:
	Test()
	{
		cout <<"Test 构造函数" << endl;
	}
	~Test()
	{
		cout <<"Test 析构函数" << endl;
	}
};

int main()
{
	Test t1;    //栈空间创建对象
	
	//创建对象 1、申请空间 2、调用构造函数初始化    c++不用malloc创建对象
	Test *pt = (Test *)malloc(sizeof(Test) * 1);       //在堆空间申请一个对象大小的内存
	if(NULL == pt)
	{
		cout << "malloc failure" << endl;
	}

	free(pt);       //释放内存,不释放对象

	return 0;
}

二、new和delete(关键字:运算符)用法

作用:创建堆内存对象,类似于malloc,但是可以自动启动类构造函数

1、new用法:

Test *pt2 = new Test;

2、delete用法

delete pt2;

#include <iostream>

using namespace std;

class Test
{
public:
	Test()
	{
		cout <<"无参构造函数" << endl;
	}
	Test(int a,int b)
	{
		cout <<"有参构造函数" << endl;
	}
	~Test()
	{
		cout << "析构函数"  << endl;
	}
};

int main()
{
	int *p1 = new int;     //给一个整数申请空间
	cout << *p1 << endl;

	delete p1;           //不delete会可能内存泄漏
	
	char *p2 = new char;  //给一个字符申请空间
	delete p2;

	int *p3 = new int(100);     //给一个整数申请空间 同时初始化100
	cout << *p3 << endl;

	delete p3;

	char *p4 = new char[10];     //给10个字符申请空间 数组
	delete[] p4;                 //释放数组加上[]
	
	Test *t1 = new Test;
	delete t1;
	
	Test *t2 = new Test(1,2);
	delete t2;

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值