简简单单学习CPP-动态对象创建
new和delete简单使用
- C语言不会调用构造和析构函数
- C++申请堆区空间和释放堆区空间使用new和delete关键字
# define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include "test.h"
using namespace std;
class Maker {
public:
Maker(int id, int age) {
cout << "有参构造函数" << endl;
mId = id;
mAge = age;
}
int getId() {
return mId;
}
int getAge() {
return mAge;
}
~Maker() {
cout << "释放" << endl;
}
private:
int mId;
int mAge;
};
class Student {
public:
Student(const char* name, int Age) {
pName = (char*)malloc(strlen(name) + 1);
strcpy(pName, name);
age = Age;
}
Student(const Student& stu) {
cout << "自己拷贝的构造函数" << endl;
pName = (char*)malloc(strlen(stu.pName) + 1);
strcpy(pName, stu.pName);
age = stu.age;
}
~Student() {
cout << "析构函数" << endl;
if (pName != NULL) {
free(pName);
pName = NULL;
}
}
private:
char* pName;
int age;
};
void test() {
Maker m1(1, 11);
Maker m2(m1);
cout << "m1 " << m1.getId() << endl;
cout << "m2 " << m2.getAge() << endl;
}
void test01() {
Maker* m = new Maker(1,1);
delete m;
}
int main() {
test01();
system("pause");
return EXIT_SUCCESS;
}
申请和释放数组空间
void test02() {
int* pInt = new int[10];
for (int i = 0; i < 10; i++) {
pInt[i] = i + 1;
}
}