qfedu-cpp-level/day3/d17.cpp

44 lines
840 B
C++
Raw Permalink Normal View History

#include <iostream>
#include <cstdlib>
using namespace std;
class A
{
private:
string name;
public:
A()
{
cout << "A()" << endl;
name = "no name";
}
A(const string &name)
{
cout << "A(const string &name)" << endl;
this->name = name;
cout << "name: " << name << endl;
}
~A()
{
cout << name << "~A()" << endl;
}
};
int main()
{
// A *p = new A[5];
// delete[] p;
// A *p2 = new A[4]{A("a"), A("b"), A("c"), A("d")};
// delete[] p2; // 释放数组中成员对象时,从高(地址)到低(地址)依次释放
A *a = new A("abc");
free(a); // 只是放指针指向的堆空间,不会调用对象的析构函数
char *a2 = (char *)malloc(sizeof(A));
delete a2; // 可以删除简单的 void* 指针
return 0;
}