c++_class
浅拷贝与深拷贝
//浅拷贝与深拷贝
//#include
using namespace std;
//
class Person
{
public:
Person()
{
cout << "默认构造函数" << endl;
}
Person(const Person& p)
{
m_Age = new int(*p.m_Age);
cout << "拷贝构造函数" << endl;
}
Person(int Age)
{
m_Age = new int(Age);//new给出一个地址
cout << "有参构造函数" << endl;
}
~Person()
{
if(m_Age != NULL)
{
delete m_Age;
m_Age = NULL;
}
cout << "析构函数" << endl;
}
int *m_Age;
};
void test()
{
Person p1(20);
cout << "年龄:" << *p1.m_Age << endl;
Person p2(p1);
cout << "年龄:" << *p2.m_Age << endl;
}
//
int main ()
{
test();
return 0;
}

浙公网安备 33010602011771号