zoukankan      html  css  js  c++  java
  • 为my_string类创建复制构造函数copy constructor ,拷贝函数名和类同名

    为下面的my_string类创建一个复制构造函数,并将定义该类的代码提交。

    my_string类的定义:

    class my_string {
       char *s;
    public:
       my_string(char *str)  {
          s = new char[strlen(str)+1];
          strcpy(s, str);
       }
       ~my_string() {
           if(s) delete [] s;
           cout << "Freeing s
    "; 
        }
       void show() { cout << s << "
    "; }
    };
    

    裁判测试程序样例:

    #include <iostream>
    #include <cstring>
    using namespace std;
    // 你提交的代码将被嵌入到这里
    
    
    int main()
    {
       char str[80];
       cin>>str;
       my_string obj(str); 
    
       my_string ob1(obj);	
       my_string ob2=ob1;
    
       ob1.show();
       ob2.show();
    
       return 0;
    }
    

    输入样例:

    ByeBye
    

    输出样例:

    ByeBye
    ByeBye
    Freeing s
    Freeing s
    Freeing s
    代码如下:
    #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
    "; 
        }
       void show() { cout << s << "
    "; }
    };
     
    int main()
    {
       char str[80];
       cin>>str;
       my_string obj(str); 
     
       my_string ob1(obj);                
       my_string ob2=ob1;
     
       ob1.show();
       ob2.show();
    }
      
    不一样的烟火
  • 相关阅读:
    ASP.NET缓存全解析(系列)
    updateprogress用法技巧
    text与img对齐
    9款Firefox插件提高设计开发效率
    ASP.NET页面实时进行GZIP压缩优化
    如何收缩和删除SQL日志文件
    闲扯加班
    与大家分享一点游戏管理晋升的心得(完整版)
    FDS (Flex Data Services)
    和我老婆去旅游
  • 原文地址:https://www.cnblogs.com/cstdio1/p/11080997.html
Copyright © 2011-2022 走看看