浅拷贝是简单的赋值拷贝操作,编译器完成。深拷贝是采用动态内存在堆区重新申请空间,进行拷贝操作。浅拷贝容易重复释放内存空间。
代码采用深拷贝操作解决浅拷贝的问题。
#define _CRT_SECURE_NO_WARNINGS 1 #includeusing namespace std; class stu { public: stu() {//无参构造函数(也是默认的构造函数) cout << "stu的无参构造函数被调用" << endl; } stu(int my_age,int my_weight) {//有参构造函数 age = my_age; weight = new int(my_weight); cout << "stu的有参构造函数被调用" << endl; } stu(const stu& p) {//拷贝构造函数 age = p.age; weight=new int(*p.weight); cout << "stu的拷贝构造函数被调用" << endl; } ~stu() {//析构函数 if (weight!=NULL) { delete weight; weight = NULL; } cout << "stu的析构函数被调用" << endl; } int age; int* weight; }; void test() { stu u1(10,100); cout << "学生的年龄是:" << u1.age << "学生的体重是:" << *u1.weight << endl; stu u2(u1); cout << "学生的年龄是:" << u2.age << "学生的体重是:" << *u2.weight << endl; } int main() { test(); return 0; }



