c++基础练习(2023-3-28)

仿照string完成mystring类

#include <iostream>
#include <cstring>
using namespace std;
class myString
{
private:
    char *str;
    int size;
public:
    //无参构造
    myString():size(10)
    {
        str = new char[size];
        cout << "无参构造"<<endl;
    }
    //有参构造
    myString(const char *s)
    {
        this->size=strlen(s);
        str = new char[size+1];
        strcpy(this->str,s);
        cout << "有参构造"<<endl;
    }
    //拷贝构造
    myString(const myString & other):str(new char(*(other.str))),size(other.size)
    {
        cout <<"拷贝构造" <<endl;
    }
    //拷贝赋值
    myString & operator = (const myString &other)
    {
        if(this != &other)
        {
        this->size = other.size;
        strcpy(this->str,other.str);
        cout <<"拷贝赋值函数"<<endl;
        }
        return *this;
    }
    //析构函数
    ~myString()
    {
        delete str;
    }
    //判空函数
    bool isEmpty()
    {
        return size==0?true:false;
    }
    //size函数
    int CharSize()
    {
        int lenth = strlen(this->str);
        return lenth;
    }
    //c_str函数
    char *c_str()
    {
        cout << this->str <<endl;
        return this->str;
    }
    //at函数
    char &at(int pos)
    {
       return *(str+pos);
    }
};
int main()
{
    myString stu;
    cout<<"*******"<<endl;

    char str[20]="hello world";
    myString stu1(str);
    cout<<"*******"<<endl;

    myString stu2(stu1);
    cout<<"*******"<<endl;

    myString stu3=stu2;
    stu3 = stu1;
    cout<<"*******"<<endl;

    myString stu4 = stu1;
    bool flag=stu4.isEmpty();
    cout << flag <<endl;
    cout<<"*******"<<endl;

    myString stu5 = stu1;
    int length = stu5.CharSize();
    cout << length <<endl;
    cout<<"*******"<<endl;

    myString stu6 = stu1;
    cout<<stu6.c_str()<<endl;
    cout<<"*******"<<endl;

    myString stu7 = stu1;
    cout<<stu7.at(1)<<endl;
    cout<<"*******"<<endl;

    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值