c++ new delete

#include <iostream>
using namespace std;
void main1()
{
	//int *p=(int *)malloc(sizeof(int));
	int *p1=new int;
	*p1=1;
	printf("%d\n",*p1);
	delete p1;
	system("pause");
}
void main2()
{
	//int *p=(int *)malloc(10*sizeof(int));
	int *p1=new int[10];
    for(int i=0;i<10;i++)
	{
	   p1[i]=i+1;
	   printf("%d\n",p1[i]);
	}
	delete [] p1;
	
	system("pause");
}
class Test1
{
private:
	int m_a;
	int m_b;
protected:
public:
	Test1(int a,int b)
	{
         m_a=a;
		 m_b=b;
		 cout<<"构造执行"<<endl;
	}
	~Test1()
	{
	    cout<<"析构执行"<<endl;
	}
};
//c++ 的new能自动的调用类的构造函数,delete 能调用类的析构函数
//malloc 不会调用类的构造函数 free 也不会调用类的析构函数
void mainplay()
{
	//Test1 t1(1,2);
	Test1 *p2=(Test1*)malloc(sizeof(Test1));
	free(p2);
	Test1 *p1=new Test1(3,4);
	delete p1;
}
int CreateTest1(Test1 **p)
{
	Test1 * tmp=new Test1(5,6);
	//p 是实参的地址 *(实参的地址)去间接修改实参的值
	*p=tmp;
	return 0;
}
int CreateTest2(Test1* &myp)
{
	myp=new Test1(5,6);
	//p 是实参的地址 *(实参的地址)去间接修改实参的值
	
	return 0;
} 
void mainaaa()
{
	//mainplay();
	Test1 *p3=NULL;
//	CreateTest1(&p3);

	CreateTest2(p3);
	delete(p3);
	system("pause");
}


#include <iostream>
using namespace std;

void main201()
{
	//malloc 的内存 可以用delete 释放吗?
	int *p2=new int(10);
	printf("%d\n",*p2);
	free(p2);

	system("pause");
}
void main202()
{
	int *p1=(int*)malloc(10*sizeof(int));
	//int *p1=new int[10];
	for(int i=0;i<10;i++)
	{
		p1[i]=i+1;
		printf("%d\n",p1[i]);
	}
	//free(p1);
	delete[]p1;
	system("pause");
}
class Test2
{
private:
	int m_a;
	int m_b;
protected:
public:
	Test2(int a,int b)
	{
         m_a=a;
		 m_b=b;
		 cout<<"构造执行"<<endl;
	}
	~Test2()
	{
	    cout<<"析构执行"<<endl;
	}
};
void main003()
{
	Test2 * tmp=new Test2(1,2);
	free(tmp);
	system("pause");
}
void main()
{
	Test2 * tmp=(Test2*)malloc(sizeof(Test2));
	//free(tmp);
	delete(tmp);
	system("pause");
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值