2月1号作业

该代码示例展示了如何在C++中创建一个名为my_string的自定义字符串类,实现了包括构造函数、赋值运算符、c_str()、length()、empty()和at()等基本字符串操作。在main函数中,对这个类的实例进行了初始化、赋值和长度、空状态等属性的检查。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:自制string类实现部分功能

代码:

main.cpp

#include <iostream>
#include<cstring>
#include<cstdlib>
#include<text1h.h>

using namespace std;

int main()
{
    my_string a1;
    my_string a2("hello");
    my_string a3="world";
    my_string a4(3,'q');
    a1="nihao";
    cout<<a1.c_str()<<endl;
    a1=a2;
    cout<<a1.c_str()<<endl;
    cout<<a2.c_str()<<endl;
    cout<<a3.c_str()<<endl;
    cout<<a4.c_str()<<endl;
    cout<<"a2.length="<<a2.length()<<endl;

    if(a3.empty())
    {
        cout<<"空"<<endl;
    }
    else
    {
        cout<<"非空"<<endl;
    }

    cout<<"a3[0]="<<a3.at(0)<<" a3[1]="<<a3.at(1)<<endl;

    return 0;
}

text1.cpp

#include<text1h.h>
#include<iostream>

char *my_string::c_str()
{
    return data;
}

int my_string::length()
{
   return strlen(data);
}

bool my_string::empty()
{
   return strlen(data)==0?1:0;
}

char my_string::at(int n)
{
   return data[n];
}

text1.h

#ifndef TEXT1H_H
#define TEXT1H_H

#include <iostream>
#include<cstring>
#include<cstdlib>
using namespace std;
class my_string
{
private:
    char *data;
    int size;
public:
    my_string():size(15)
    {
        data=new char[size];
        data[0]='\0';
    }

    my_string(const char* str):size(15)
    {
        data=new char[size];
        strcpy(data,str);
    }

    my_string(int n,char str):size(15)
    {
        data=new char[size];

        for(int i=0;i<n;i++)
        {
            data[i]=str;
        }
        data[n]='\0';
    }

    my_string(const my_string &other):size(other.size)
    {
        strcpy(data,other.data);
    }

    my_string & operator=(const my_string & other)
    {
        this->size=other.size;
        strcpy(data,other.data);
        return *this;
    }

    ~my_string()
    {
        delete [] data;
        data=nullptr;
    }
    char *c_str();


    int length();


    bool empty();


    char at(int n);
};
#endif // TEXT1H_H

运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值