1-malloc.cpp
#include <iostream>
#include <stdlib.h>
using namespace std;
class Test
{
public:
Test()
{
cout << "Test构造函数" << endl;
}
~Test()
{
cout << "Test析构函数" << endl;
}
};
int main()
{
//Test t1; //栈空间创建对象
//创建对象 1、申请空间 2、调用构造函数初始化 C++中不用malloc创建对象
Test *pt = (Test *)malloc(sizeof(Test) * 1); //在堆空间申请一个对象大小的内存
if (NULL == pt)
{
cout << "malloc failure" << endl;
}
free(pt); //释放内存,不是释放对象
Test *pt2 = new Test; //1、申请内存(堆) 2、调用构造函数 自动调用构造函数
delete pt2; //调用析构函数
return 0;
}
2-new.cpp
#include <iostream>
using namespace std;
class Test
{
public:
Test()
{
cout << "无参构造函数" << endl;
}
Test(int a, int b)
{
cout << "有参构造函数" << endl;
}
~Test()
{
cout << "析构函数" << endl;
}
};
int main()
{
int *p1 = new int; //给一个整数申请空间
cout << *p1 << endl;
delete p1;
char *p2 = new char; //给一个字符申请空间
delete p2;
int *p3 = new int(100); //给一个整数申请空间同时初始化为100
cout << *p3 << endl;
delete p3;
char *p4 = new char[10]; //给十个字符申请空间
delete[] p4;
Test *t1 = new Test;
delete t1;
Test *t2 = new Test(1, 2);
delete t2;
return 0;
}
3-对象初始化列表.cpp
#include <iostream>
using namespace std;
class Date
{
private:
int year;
int mouth;
int day;
public:
/*Date()
{
year = 1999;
mouth = 1;
day = 1;
}*/
Date(int y, int m, int d)
{
year = y;
mouth = m;
day = d;
}
};
//对象初始化列表:1、类对象作为成员变量并且该类没有提供无参构造函数 2、成员变量被const修饰(初始化和赋值不同)
class Student
{
private:
const int id;
Date birth;
public:
Student(int i, int y, int m, int d) : birth(y, m, d), id(i)
{
}
};
int main()
{
Student s1(1, 1999, 2, 2);
return 0;
}