wordpress阿里巴巴国际站,抄袭网站违法,临沂网站案例,竞价托管公司联系方式面试题#xff1a;
1、两种方式的区别#xff1a;
#xff08;1#xff09;malloc需要强制类型转换#xff0c;new不需要
#xff08;2#xff09;malloc需要计算空间大小#xff0c;new不需要
例如#xff1a;创建5个int类型的空间
int*p(int *)malloc(sizeof(i…面试题
1、两种方式的区别
1malloc需要强制类型转换new不需要
2malloc需要计算空间大小new不需要
例如创建5个int类型的空间
int*p(int *)malloc(sizeof(int)*5)--------malloc
int*pnew int[5]------------------------------new
(3)malloc/free是库函数而new/delete是运算符
(4)在c中malloc/free不会自动调用析构函数new/delete会自动调用析构函数 2、已经有了malloc/free为什莫还要有new/delete
答malloc/free不会自动调用析构函数new/delete会自动调用析构函数 malloc/free不会自动调用析构函数 #include iostream
#include string.h
using namespace std;class student
{
public://构造函数student(string _name,int _age){name _name;age _age;cout name age 岁了 endl;}//析构函数系统自动定义自动调用~student(){cout 析构函数 endl;}
private:string name { 0 };int age 0;char sex { 0 };int id 0;
};int main()
{
/*********************创建空间************************************/student* s1 (student*)malloc(sizeof(student*));
/*********************释放空间************************************/free (s1);return 0;
}
运行结果无析构函数 new/delete会自动调用析构函数 #include iostream
#include string.h
using namespace std;class student
{
public://构造函数student(string _name,int _age){name _name;age _age;cout name age 岁了 endl;}//析构函数系统自动定义自动调用~student(){cout 析构函数 endl;}
private:string name { 0 };int age 0;char sex { 0 };int id 0;
};int main()
{
/********************创建空间*************************/student* s1 new student(王华,26);
/********************释放空间*************************/delete s1;return 0;
}
运行结果