自定义复制构造函数

来源:互联网 发布:qq绿标安全域名生成 编辑:程序博客网 时间:2024/06/06 03:36

         c++类的创建过程中,如果你只是创建一个空类,系统会自动添加默认构造函数,以及一个默认复制构造函数。在主函数中:

复制构造函数只能用于对象的初始化,初始化的发生有以下三种情况:

①当一个对象的副本被作为参数传递给函数时,

②当用同一个类的对象给另一个新对象赋值时时,

③对象作为函数的返回值


my_string s1(),s3(5);//调用构造函数
s3=s1;//调用复制用算符(’=‘已重载)

my_string  s2(s1);     //①当一个对象的副本被作为参数传递给函数时,
my_string s2=s1;  //②当用同一个类的对象给另一个新对象赋值时时,
my_string  f()       // ③对象作为函数的返回值
{
   my_string   s5;
  .
  .
  .
   return   s5;
}





#include <iostream>#include <cstring>using namespace std;class my_string {   char *s;public:   my_string(char *str)     {      s = new char[strlen(str)+1];      strcpy(s, str);    }    my_string(const my_string &obj) //复制构造函数    {      s = new char[strlen(obj.s)+1];      strcpy(s,obj.s);    }   ~my_string() {       if(s) delete [] s;       cout << "Freeing s\n";     }   void show() { cout << s << "\n"; }};int main(){   char str[80];   cin>>str;   my_string obj(str);    my_string ob1(obj);   my_string ob2=ob1;   ob1.show();   ob2.show();