#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
class person
{
public:
person()
{
}
//初始化属性
person(char * name, int age)
{
m_name = (char*)malloc(strlen(name) * 1);
strcpy(m_name,name);
m_age = age;
}
//自己提供拷贝构造,原因简单的拷贝构造会释放堆区两次,导致挂掉 //深拷贝
person(const person&p)
{
m_age = p.m_age;
m_name = (char*)malloc(strlen(p.m_name) + 1);
strcpy( m_name, p.m_name);
}
//拷贝构造 系统会提供默认拷贝构造,而且是简单的值拷贝//浅拷贝
~person()
{
cout << "析构函数调用" << endl;
if(m_name != NULL)
{
free(m_name);
m_name = NULL;
}
}
char * m_name;
int m_age;
};
void test1()
{
person p1("敌军",10);
person p2(p1); //调用了拷贝构造
}
int main()
{
test1();
system("pause");
return EXIT_SUCCESS;
}
网友评论