qfedu-cpp-level/day3/d15.cpp

52 lines
982 B
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 动态创建对象(malloc / realloc / calloc 在堆中创建空间, new 关键字)
#include <iostream>
#include <cstdlib>
using namespace std;
class A
{
private:
int x;
public:
A(int x)
{
this->x = x;
cout << "A(int)" << endl;
}
~A()
{
cout << "~A()" << endl;
}
public:
void init(int x)
{
this->x = x;
cout << "init(int)" << endl;
}
void clean()
{
cout << "clean()" << endl;
}
};
int main()
{
// 1) 使用 malloc 方式创建
// cout << "A size is " << sizeof(A) << endl;
// A *a1 = (A *)malloc(sizeof(A));
// // a1->A(20); // 不允许显式调用构造函数
// a1->init(20); // 初始化数据
// a1->clean(); // 释放数据的空间
// a1->~A(); // 析构函数可以显式调用
// free(a1);
// 2) new 方式创建delete释放
A *a1 = new A(1);
delete a1; // 用完之后直接 delete 释放空间
return 0;
}