首页 > 编程语言 >C++从入门到精通——new和delete使用

C++从入门到精通——new和delete使用

时间:2022-11-01 18:33:55浏览次数:56  
标签:include cout int C++ Person new test01 delete


malloc 与 new 区别

  1. malloc与free 属于库函数new和delete 属于运算符
  2. malloc不会调用构造函数 new 会调用构造函数
  3. malloc 返回void * ,c++之下需要进行 强制转换,new 返回创建对象的指针
#include <iostream>
#include <string>
using namespace std;
class Person{
public:
Person(){
cout<<"构造函数调用"<<endl;
}
Person(int a){
cout<<"有参构造函数调用"<<endl;
}
~Person(){
cout<<"Person析构函数调用"<<endl;
}
};
void test01(){
Person * p = new Person;
delete p;
}
int main(){
test01();
system("pause");
return EXIT_SUCCESS;
}

C++从入门到精通——new和delete使用_#include


利用malloc申请

#include <iostream>
#include <string>
using namespace std;
class Person{
public:
Person(){
cout<<"构造函数调用"<<endl;
}
Person(int a){
cout<<"有参构造函数调用"<<endl;
}
~Person(){
cout<<"Person析构函数调用"<<endl;
}
};
void test01(){
Person *p = (Person *)malloc(sizeof(Person));

free(p);
}
int main(){
test01();
// system("pause");
return EXIT_SUCCESS;
}

C++从入门到精通——new和delete使用_开发语言_02

不要用void 接受new出来的对象,利用void无法调用析构函数

#include <iostream>
#include <string>
using namespace std;
class Person{
public:
Person(){
cout<<"构造函数调用"<<endl;
}
Person(int a){
cout<<"有参构造函数调用"<<endl;
}
~Person(){
cout<<"Person析构函数调用"<<endl;
}
};
void test01(){
void *p = new Person;
delete p;
}
int main(){
test01();
// system("pause");
return EXIT_SUCCESS;
}

C++从入门到精通——new和delete使用_#include_03

利用new开辟数组,一定调用默认构造函数

#include <iostream>
#include <string>
using namespace std;
class Person{
public:
Person(){
cout<<"构造函数调用"<<endl;
}
Person(int a){
cout<<"有参构造函数调用"<<endl;
}
~Person(){
cout<<"Person析构函数调用"<<endl;
}
};
void test01(){
// 堆区开辟数组,一定调用默认构造函数
Person *pPerson = new Person[10];
delete [] pPerson;
}
int main(){
test01();
// system("pause");
return EXIT_SUCCESS;
}

C++从入门到精通——new和delete使用_函数调用_04

#include <iostream>
#include <string>
using namespace std;
class Person{
public:
Person(){
cout<<"构造函数调用"<<endl;
}
Person(int a){
cout<<"有参构造函数调用"<<endl;
}
~Person(){
cout<<"Person析构函数调用"<<endl;
}
};
void test01(){
// 堆区开辟数组,一定调用默认构造函数
Person pArray[10] = {
Person(10),
Person(20),
Person(20),
Person(20)
};
}
int main(){
test01();
// system("pause");
return EXIT_SUCCESS;
}

C++从入门到精通——new和delete使用_函数调用_05


标签:include,cout,int,C++,Person,new,test01,delete
From: https://blog.51cto.com/u_13859040/5814692

相关文章