C++实现String类

C++实现String类

@(C++代码)[C++实现, 学习笔记]

String.h

#ifndef String_h
#define String_h

#include <iostream>
#include <cstring>

using namespace std;

//类的构建
class String
{
    friend ostream& operator<<(ostream& out,String& s);
    friend istream& operator>>(istream& in ,String& s);
public:
    String(const char* c=NULL);
    String(const String &s);
    String operator+(const String &s);
    String operator=(const String &s);
    bool operator==(const String &s);
    char operator[](int index);
    ~String(void){delete[] str;}
    size_t size(){return strlen(str);}

//private:
    char* str;
};

//功能的实现
inline String::String(const char* c)
{
    if(!c)
    {
        str = NULL;
    }
    else
    {
        str = new char[strlen(c)+1];
        strcpy(str,c);
    }
}

inline String::String(const String &s)
{
    if(!s.str)
    {
        str = NULL;
    }
    else
    {
        str = new char[strlen(s.str)+1];
        strcpy(str,s.str);
    }
}

inline String String::operator=(const String &s)
{
    if(this!=&s)
    {
        delete[] str;
        if(!s.str)
        {
            str = NULL;
        }
        else
        {
            str = new char[strlen(s.str)+1];
            strcpy(str,s.str);
        }
    }
    return *this;
}

inline String String::operator+(const String &s)
{
    String newStr;
    if(!s.str)
    {
        newStr = *this;
    }
    else if(!str)
    {
        newStr = s;
    }
    else
    {
        newStr.str = new char[ strlen(str) + strlen(s.str) + 1];
        strcpy(newStr.str , str);
        strcat(newStr.str , s.str);
    }
    return newStr;
}

inline bool String::operator==(const String &s)
{
    if(strlen(str) != strlen(s.str))
        return false;

    if(strcmp(str,s.str)==0)
        return true;
    else
        return false;
}

inline char String::operator[](int index)
{
    return str[index];
}

ostream& operator<<(ostream& out, String &s)
{
    out << s.str;
    return out;
}

istream& operator>>(istream& in , String& s)
{
    char tmp[255];
    s = "";
    do
    {
        in.get(tmp, 255);
        s = s + tmp;
    }while(tmp[0]!=0);
    return in;
}

#endif /* String_h */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值