C++构造函数

仿照string类,写一个my_string类

代码实现

#include <iostream>
#include <string.h>

using namespace std;
class my_string
{
private:
    char *str;
    int len;
public:

    //无参构造
    my_string(){}
    //有参构造
    my_string(char *q,int i)
    {
        str=new char[128];
        strcpy(str,q);
        len = i;
        cout<<"this is a has parament constroctor"<<endl;
    }
    //拷贝构造
    my_string(const my_string &O)
    {
        str=new char[128];
        this->len = O.len;
        strcpy(str,O.str);
    }
    //拷贝赋值
    my_string& operator=(const my_string &O)
    {
        if(this!=&O)
        {
            len = O.len;
            str = new char[128];
            strcpy(str,O.str);
        }
        return *this;
    }
    //bool my_empty()        判空
    bool my_empty()
    {
        if(*str='\0')
            return true;
        else
            return false;

    }
    //int my_size()          求长度
    int my_size()
    {
        int i=0;
        while(*(str+i)!=0)
        {
            i++;
        }
        return i;
    }
    //转化为c风格字符串
    char *my_str()
    {
        return str;
    }
};
int main()
{
    //验证有参构造
       my_string str1("hello world!",10);
       cout<<"str1:"<<str1.my_str()<<endl;
       my_string str2("h",10);
       cout<<"str2:"<<str2.my_str()<<endl;

       //验证拷贝构造
       my_string str3=str1;
       cout<<"str3"<<str3.my_str()<<endl;

       //验证赋值构造
       my_string str4;
       str4=str3;
       //验证判空
       my_string str5("",0);
       if(str5.my_empty())
           cout<<" no str5"<<endl;
       else
           cout<<"have str5"<<endl;

       if(str4.my_empty())
           cout<<"no str4"<<endl;
       else
           cout<<"have str4"<<endl;
       //获取长度
       int len=str1.my_size();
       cout<<"the lenth of str1:"<<len<<endl;

    cout << "Hello World!" << endl;
    return 0;
}


运行结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值