8.6.3 解决方案—显式定义复制构造函数
如果类中含有指针型的数据成员、需要使用动态内存,程序员最好显式定义自己的复制构造函数,避免各种可能出现的内存错误,见代码8.11。
代码8.11 显式定义复制构造函数DefineOwnCopyConstructor
<—————————————文件名:computer.h———————————————-> 01 #include<iostream> 02 #include<cstring> 03 using namespace std; 04 class computer 05 { 06 private: 07 char*brand; 08 float price; 09 public: 10 computer(const char*sz,float p) 11 { 12 brand=new char[strlen(sz)+1]; 13 strcpy(brand,sz); 14 price=p; 15 } 16 computer(const computer&cp)//自定义复制构造函数 17 { 18 brand=new char[strlen(cp. brand)+1];//重新为brand开辟于cp.brand 19 //同等大小的动态内存 20 strcpy(brand,cp. brand);//字符串复制 21 price=cp. price; 22 } 23 ~computer() 24 { 25 delete[]brand; 26 cout<<"清理现场"<<endl; 27 } 28 void print() 29 { 30 cout<<"品牌:"<<brand<<endl; 31 cout<<"价格:"<<price<<endl; 32 } 33 }; <———————————文件名:example811.cpp————————————————> 34 #include"computer.h" 35 int main() 36 { 37 computer comp1("Dell",7000);//调用有参构造函数声明computer类 38 //对象comp1,并初始化 39 comp1. print(); 40 //调用复制构造函数声明computer类对象comp2,并用comp1为其初始化 41 computer comp2(comp1);comp2. print(); 42 return 0; 43 }
输出结果如下所示。
品牌:Dell 价格:7000 品牌:Dell 价格:7000 清理现场 清理现场
【代码解析】在代码第16行,显式定义了computer类的复制构造函数,没有采用“brand=cp.brand”这种直接指针赋值,而是重新申请了一块动态内存,使用库函数strcpy()实现了字符串的复制,这样,comp1.brand和comp2.brand指向不同的两块动态内存,避免了可能出现的错误。