qfedu-cpp-level/day3/d5.cpp

55 lines
1016 B
C++
Raw Permalink Normal View History

// 创建类对象的指针
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
class A
{
public:
char *msg;
public:
A()
{
this->msg = (char *)malloc(30);
strcpy(this->msg, "haha");
}
A(const char *msg)
{
this->msg = (char *)malloc(30);
strcpy(this->msg, msg);
}
~A()
{
cout << this << "release msg : " << this->msg << endl;
free(this->msg);
// free(this);
}
};
int main()
{
A *a1 = new A;
cout << "a1->msg: " << a1->msg << endl;
A *a2 = new A("disen 666");
cout << "a2->msg: " << a2->msg << endl;
// 【注意】指针释放空间时, 不会自动执行对象的析构函数
// 可以通过手动调用 对象的析构方法 或使用 delete
a1->~A();
free(a1);
// a2->~A();
// delete a1;
delete a2;
A a3;
// 注意: delete 只能删除 new 出来的对象,即对象的指针
// A &a4 = a3;
// delete &a4;
return 0;
}