#include <iostream>
using namespace std;
class Test {
public:
Test() {
p = (char*)malloc(512);
if (p != NULL) strcpy_s(p, "11111");
cout << "我是构造函数,自动被调用了" << endl;
}
~Test() {
cout << "我是析构函数,自动被调用了" << endl;
if (p != NULL) {
cout << "free(p)" << endl;
free(p);
}
}
protected:
private:
int a;
char* p;
};
void test() {
Test t, t1;
cout << "展示t生命周期" << endl;
}
void main()
{
test();
system("pause");
}
补充start:C++构造和析构
最新推荐文章于 2024-03-28 09:30:00 发布
本文探讨了C++中Test类的构造函数和析构函数使用,重点在于malloc动态内存的分配与释放,以及生命周期管理。通过实例展示了如何在类中正确运用这些概念,并附带了main函数和test函数的完整代码示例。
5382

被折叠的 条评论
为什么被折叠?



