• String类(资源空间问题、深复制与浅复制)


    【问题描述】
    自行编写代码完成自己的String类。注意这里的String字符S大写,主要目的是与C++自带的string类相互区分。

    class String //请勿修改本类的声明,请实现具体的成员函数。
    {
    public:
      String(const char *str=NULL);  //构造函数
      String(const String &r);  //拷贝构造函数
      ~String();  //析构函数
    private:
      char *mydata;  //请勿修改数据成员的类型
    };
    int main() //请勿修改主函数
    {
      String s1,s2("hello");
      String s3(s2);
      return 0;
    }
    

    请在构造函数、拷贝构造函数、析构函数的函数体里添加相应的cout语句,输出对应的提示。

    【输入形式】 无输入

    【输出形式】 构造函数、拷贝构造函数和析构函数里的提示语句

    【样例输入】

    【样例输出】
    gouzao
    gouzao hello
    kaobei gouzao hello
    xigou hello
    xigou hello
    xigou

    #include <iostream>
    #include <string.h>
    using namespace std;
    
    class String
    {
    public:
        String(const char *str=NULL);//构造函数
        String(const String &r);//拷贝构造函数
        ~String();//析构函数
    private:
        char *mydata;
    };
    
    String::String(const char *str)//构造函数
    {
        if( str==NULL )
        {
            cout << "gouzao" << endl;
            mydata = NULL;
        }
        else
        {
            cout << "gouzao " << str << endl;
            int len = strlen(str);
            mydata = new char[len+1];
            strcpy(mydata,str);
        }
    }
    
    String::String(const String &r)//拷贝构造函数
    {
        cout << "kaobei gouzao " << r.mydata << endl;
        int len = strlen(r.mydata);
        mydata = new char[len+1];
        strcpy(mydata,r.mydata);
    }
    
    String::~String()//析构函数
    {
        if( mydata==NULL )
        {
            cout << "xigou" << endl;
        }
        else
        {
            cout << "xigou " << mydata << endl;
        }
        delete [] mydata;
    }
    
    int main() //请勿修改主函数
    {
        String s1,s2("hello");
        String s3(s2);
        return 0;
    }
    
    
  • 相关阅读:
    Typora Writings
    Xcode7.3 beta 新功能
    最美应用API接口分析
    'Project Name' was compiled with optimization
    web前端开发与iOS终端开发的异同[转]
    2015-12-19_16_30_15
    Xcode搭建Python编译环境
    jsPach.qq.com
    Q&AApple’s Craig Federighi talks open source Swift, Objective-C and the next 20 years of development
    .NET Core项目与传统vs项目的细微不同
  • 原文地址:https://www.cnblogs.com/yuzilan/p/10626150.html
Copyright © 2020-2023  润新知