#include
#include
using namespace std;
// 构造函数 (拷贝构造函数), 析构函数,
/* 深拷贝: 是指编译器给类提供定默认拷贝构造函数拷贝含有指针成员对象时,
调用默认析构函数多次释放堆中同一块内存, 导致内存访问异常.
解决办法: 自定义拷贝构造函数, 针对指针成员,
用 new 关键字开辟另一块堆内存, 存放拷贝对象的指针成员.
*/
class Student
{
public:
Student() {}
// 默认析构函数
/*
Student( Student &stu)
{
m_age = stu.m_age;
p = stu.p;
}
*/
// 自定义析构函数
Student(const Student &stu)
{
m_age = stu.m_age;
p = new int(*stu.p);
}
void showStudent()
{
cout << m_age << endl;;
cout << *p << endl;
cout << "" << endl;
}
//private:
int m_age;
int *p;
};
int main()
{
int a = 6;
//Student s1(10,&a) 错误操作, 自定义析构函数之后, 编译器不再提供默认普通构造函数来初始化;
Student s1;
s1.m_age = 10;
s1.p = &a;
Student s2=s1;
s1.showStudent();
s2.showStudent();
system("pause");
return 0;
// 构造函数
来源: http://www.bubuko.com/infodetail-3320718.html