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

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值