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();
    }
      
    不一样的烟火
  • 相关阅读:
    分布图
    针对回归训练卷积神经网络
    polyfit 多项式曲线拟合matlab
    Re-run failed tests in testng
    URI 和 URL的区别
    十分钟理解Gradle
    移动App测试实战—专项测试(转)
    adb 常用命令
    MySQL基本操作
    Java注解
  • 原文地址:https://www.cnblogs.com/cstdio1/p/11080997.html
Copyright © 2011-2022 走看看