new和delete的使用:
#include <iostream>
using namespace std;
void Demo01()
{
int *p = new int(10); //new一个内存,顺便赋值成10 *p = 10;
//*p = 1;
delete p;
system("pause");
}
void Demo02()
{//分配数组
int *p = new int[10];
for (int i = 0; i < 10; ++i)
{
p[i] = i + 1;
printf("%d ", p[i]);
}
//delete p; //没释放完
delete[]p; //释放数组
}
class Test01
{
public:
Test01(int a, int b)
{
m_a = a;
m_b = b;
cout << "构造执行" << endl;
}
~Test01()
{
cout << "析构执行" << endl;
}
protected:
private:
int m_a;
int m_b;
};
//c++中的new可以自动调用类中的构造函数,delete可以自动调用析构函数
//与之对应的malloc不会调用类的构造函数,free也不会调用类的析构函数
void Demo03()
{//new对象
Test01 t1(1, 2);
Test01 *t2 = new Test01(3, 4);
Test01 *t3 = (Test01 *)malloc(sizeof(Test01));
free(t3);
delete t2;
}
int CreateTest01(Test01 **p)
{
Test01 *tmp = new Test01(5, 6);
*p = tmp;
return 0;
}
int CreateTest02(Test01 *&p)
{
Test01 *tmp = new Test01(5, 6);
p = tmp;
return 0;
}
void Demo04()
{//指针做函数参数
Test01 *p = NULL;
CreateTest01(&p);
CreateTest02(p);
}
void main()
{
Demo03();
system("pause");
}
new和delete的进阶:
#include <iostream>
using namespace std;
void Demo01()
{//基础类型没问题
int *p = new int(10);
printf("%d \n", *p);
free(p);
}
void Demo02()
{//数组类型也没问题
int *p = new int[10];
for (int i = 0; i < 10; ++i)
{
p[i] = i + 1;
printf("%d ", p[i]);
}
cout << endl;
free(p);
}
void Demo03()
{//基础类型没问题
int *p = (int *)malloc(sizeof(int));
*p = 10;
printf("%d \n", *p);
delete p;
}
void Demo04()
{//数组类型也没问题
int *p = (int *)malloc(sizeof(int) * 10);
for (int i = 0; i < 10; ++i)
{
p[i] = i + 1;
printf("%d ", p[i]);
}
cout << endl;
delete p;
}
class Test01
{
public:
Test01(int a, int b)
{
m_a = a;
m_b = b;
cout << "构造执行" << endl;
}
~Test01()
{
cout << "析构执行" << endl;
}
private:
int m_a;
int m_b;
};
void Demo05()
{
Test01 *tmp = new Test01(5, 6);
free(tmp);//不会调用析构函数,因此不推荐用free
}
void Demo06()
{
Test01 *tmp = (Test01 *)malloc(sizeof(Test01)); //malloc不会调用构造函数
delete tmp;//delete会调用析构函数
}
void Demo07()
{
int *p = new int[10];
for (int i = 0; i < 10; ++i)
{
p[i] = i + 1;
printf("%d ", p[i]);
}
delete[](p + 1);
}
void main()
{
//Demo01();
//Demo02();
//Demo06();
Demo07();
system("pause");
}