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();
    }
      
    不一样的烟火
  • 相关阅读:
    LeetCode 23. 合并K个排序链表
    LeetCode 199. 二叉树的右视图
    LeetCode 560. 和为K的子数组
    LeetCode 1248. 统计「优美子数组」
    LeetCode 200. 岛屿数量
    LeetCode 466. 统计重复个数
    LeetCode 11. 盛最多水的容器
    LeetCode 55. 跳跃游戏
    LeetCode 56. 合并区间
    Java生鲜电商平台-订单架构实战
  • 原文地址:https://www.cnblogs.com/cstdio1/p/11080997.html
Copyright © 2011-2022 走看看