1.malloc和new的区别
malloc和free属于库函数 new和delete属于运算符
malloc不会调用构造函数 new会调用构造函数
malloc返回void* C++下要强转 new会返回创建对象的指针
2.注意事项
不要用void*来接收new出来的对象,利用void*是无法调用析构函数
3.利用new来创建数组
int *pInt = new int[10];
double *pDouble = new double[10];
释放数组的时候要加[]
Person *pPerson = new Person[10];
//释放数组的时候要加[]
delete [] pPerson;
栈上开辟数组,可以没有默认构造。堆区开辟数组 一定会调用默认构造函数
整体代码:
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
class Person
{
public:
Person()
{
cout << "Person构造函数调用" << endl;
}
Person(int a)
{
cout << "Person的有参构造函数调用" << endl;
}
~Person()
{
cout << "Person析构函数的调用" << endl;
}
};
//malloc和new的区别
//malloc和free属于库函数 new和delete属于运算符
//malloc不会调用构造函数 new会调用构造函数
//malloc返回void* C++下要强转 new会返回创建对象的指针
void test01()
{
Person *p = new Person;
delete p;
}
//注意事项 不要用void*来接收new出来的对象,利用void*是无法调用析构函数
void test02()
{
void *p = new Person;
delete p;
}
//利用new来开辟数组
void test03()
{
int *pInt = new int[10];
double *pDouble = new double[10];
//堆区开辟数组 一定会调用默认构造函数
/*Person *pPerson = new Person[10];*/
//释放数组的时候要加[]
/*delete [] pPerson;*/
//栈上开辟数组,可以没有默认构造
Person pArray[10] = { Person(10), Person(20) };
}
int main()
{
//test01();
//test02();
test03();
system("pause");
return EXIT_SUCCESS;
}