12.6 c++练习

代码: 

#include <iostream>
#include <cstring>
using namespace std;

class My_string
{
  private:
    char *cstr;
    int len;

  public:
    My_string()  //无参构造
    {
        cstr=new char{};
        len=0;
    }
    My_string(const char *str) //有参构造
    {
        len=strlen(str);
        cstr=new char[len];
        strcpy(cstr,str);
    }
    My_string(const My_string &other) //拷贝构造
    {
        len=other.len;
        cstr=new char[len];
        strcpy(cstr,other.cstr);
    }
    ~My_string() //析构函数
    {
        delete cstr;
    }

    bool empty() //判断是否为空
    {
        if(len==0)
        return true;

        return false;
    }
    int size()//返回字符串的长度
    {
        return len;
    }
    char &at(int index) //
    {
        return cstr[index];
    }
    char* c_str() //转化为C风格字符串
    {
        return cstr;
    }

    void show()
    {
        cout<<"字符串:"<<cstr<<endl;
        cout<<"长度:"<<len<<endl;
    }
};
int main()
{
    My_string s;
    s.show();
    if(s.empty())
    {
        cout<<"s为空"<<endl;
    }
    else
    {
        cout<<"s不为空"<<endl;
    }
    cout<<"**********************"<<endl;
    My_string s1("jinghao");
    s1.show();
    if(s1.empty())
    {
        cout<<"s1为空"<<endl;
    }
    else
    {
        cout<<"s1不为空"<<endl;
    }
    s1.at(0)='J';
    cout<<s1.c_str()<<endl;
    cout<<"**********************"<<endl;
    My_string s2(s1);
     s2.show();
    if(s2.empty())
    {
        cout<<"s2为空"<<endl;
    }
    else
    {
        cout<<"s2不为空"<<endl;
    }



    return 0;
}

代码运行: 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值