首先拷贝构造函数的声明方法:
类名::类名(const 类名&)
1、浅拷贝的实现程序:
#include "stdafx.h" #include <iostream> #include <cstring> using namespace std; class Person { public: //构造函数 Person(const char *name, double hei, double wei, int age0):height(hei),weight(wei),age(age0){ cout << "Person ctor called .\n"; pName = new char[strlen(name) + 1]; strcpy(pName, name); } //析构函数 ~Person(){ cout << "deleting pName"; delete[] pName; } //类Person的拷贝构造函数 Person(const Person &person){ cout << "Person copy ctor called"; pName = person.pName; height = person.height; weight = person.weight; age = person.age; } private: char *pName; double height; double weight; int age; }; int main() { Person p1("Leekin",175,185,25); Person p2(p1); return 0; }
首先这个程序在VS2013上面编译不通过;是因为浅拷贝存在风险:非法操作内存,究其原因是因为“拷贝不充分”导致堆中的某一块内存被不同对象的指针属性同时指向,该内存不可避免的被释放多次,这是不应许。第一次被释放的空间已经属于操作系统,当在一次释放时那一片空间已经不属于程序了。
以下是浅拷贝的内存模型:
2、深拷贝可以避免由于浅拷贝带来的问题,即让拷贝函数做好充分的拷贝,程序如下:
#include "stdafx.h" #include <iostream> using namespace std; class Person { public: //构造函数 Person(const char *name, double hei, double wei, int age0):height(hei),weight(wei),age(age0){ cout << "Person ctor called .\n"; pName = new char[strlen(name) + 1]; strcpy(pName, name); } //析构函数 ~Person(){ cout << "deleting pName"; delete[] pName; } //类Person的拷贝构造函数 Person(const Person &person){ cout << "Person copy ctor called"; pName = person.pName; height = person.height; weight = person.weight; age = person.age; //深拷贝:重新申请一块内存 pName = new char[strlen(person.pName) + 1]; strcpy(pName, person.pName); } private: char *pName; double height; double weight; int age; }; int main() { Person p1("Leekin",17.5,18.5,25); Person p2(p1); return 0; }
深拷贝的内存模型: