#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
class Person
{
public:
Person()
{
cout << "无参构造" << endl;
}
Person(int a)
{
cout << "有参构造" << endl;
}
~Person()
{
cout << "析构函数" << endl;
}
};
void test01()
{
//Person p1; 默认对象是在栈区开辟
Person * p2 = new Person; //堆区开辟
//1.所有new出来的对象 都会返回该类型的指针,malloc只会返回void指针,所以还需要强转
//2.malloc不会调用构造函数而new会调用构造
//3.new,delete是运算符 malloc,free是函数,各自配合使用,不要混用
delete p2;
}
void test02()
{
//通过new开辟数组 一定会调用默认构造函数,所以一定要提供默认构造
Person * pArray = new Person[10];
//Person pArray2[2] = { Person(1), Person(2) }; //在栈上开辟数组,可以指定有参构造
//释放数组 delete []
delete[] pArray;
}
int main() {
//test01();
test02();
system("pause");
return EXIT_SUCCESS;
}