封装C++函数中的string函数(低配版)

该代码示例展示了如何在C++中创建一个自定义的mystring类,包括初始化构造函数、从字符数组构造、拷贝构造以及析构函数。mystring对象s1从用户输入的字符数组buf创建,然后s2通过拷贝构造函数从s1创建,展示了对象间的复制过程。
摘要由CSDN通过智能技术生成

代码如下:

#include <iostream>
#include <string.h>
using namespace std;

class mystring
{
public:
    int size=20;
    char *str;
    mystring(int size):str(new char(size)+1)
    {
        cout << "构造函数" << endl;
    };

    mystring(char *buf)
    {
        this->size = strlen(buf);
        str = new char(size);
        strcpy(str,buf);
    }

    mystring(mystring &s):size(s.size)
    {
        cout<<"s2中的字符串大小为" <<this->size <<endl;
        this->str = new char(size);
        strcpy(this->str,s.str);
        cout << "拷贝完毕" <<endl;
    }

    ~mystring()
    {
        delete str;
        cout <<"析构完毕"<<endl;
    }



};

int main()
{

    char buf[20];
    cin >> buf;
    cout << "s1中的字符串内容为" << buf <<endl;
    int size = strlen(buf);     //字符串大小
    cout <<"s1中的字符串大小为" << size <<endl;
    mystring s1(buf);
    mystring s2 = s1;
    cout << "s2中的字符串内容为" << s2.str <<endl;

    return 0;
}

效果图如下:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值