#include <iostream>
#include <string>
using namespace std;
class Student
{
public:
Student() {
cout << "默认构造函数" << endl;
};
Student(int a, int s)
{
cout << "有参构造函数" << endl;
age = a;
salary = new int(s); // 这里
}
Student(const Student &s)
{
age = s.age;
//salary = s.salary; 这里,浅拷贝就是直接赋值。
salary = new int(*s.salary);// 深拷贝是在堆上开辟新的空间。 这就是拷贝构造中,涉及到指针属性的深拷贝
cout << "拷贝构造函数" << endl;
}
~Student() {
if (salary != NULL) { // 这里
delete salary;
salary = NULL;
}
cout << "析构函数" << endl;
}
int age;
int *salary;
};
int main() {
Student s(22,6000);
Student s1(s);
cout << *s.salary << " "<< *s1.salary << endl;
return 0;
}