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;
}

posted @ 2018-12-25 19:54  Sherry_Yue  阅读(389)  评论(0编辑  收藏  举报