#include<iostream>
using namespace std;
/*
c语言中 malloc free
c++语言中 new delete 之间的区别
*/
void main1() {
int* p = (int*)malloc(sizeof(int));//c语言分配基础数据类型
free(p);// c语言释放基础数据
int* p1 = new int(10); // c++中分配基础数据类型
delete p1; //c++中释放基础数据类型
system("pause");
}
void main2() {
int* p = (int*)malloc(sizeof(int) * 10);//c语言分配数组
free(p);//c语言释放数组变量
int* p1 = new int[10];//c++分配数组
delete[] p1; //c++释放数组
system("pause");
}
class Test {
public:
Test(int a) {
this->a = a;
cout << "构造函数被调用" << endl;
}
~Test() {
cout << "析构函数被调用" << endl;
}
private:
int a;
};
int main() {
//C语言分配对象
Test* t = (Test*)malloc(sizeof(Test));
free(t);
//c++语言分配对象
Test* t1 = new Test(1);
delete t1;
system("pause");
}
c语言的 malloc 与 free 和 c++语言的 new 与 delete 的区别 是: 在生成对象时, 使用new 与 delete 会调用构造函数与析构函数。很显然,new与delete是c++提出的概念,所以他一定具有c++初始化对象的特点/
另外,他们还支持混搭风,即malloc生成对象可以通过delete进行释放。
new生成的对象可以通过free进行释放。