C++ 实现一个String类

//头文件

#ifndef     STRING_H    
#define  STRING_H
 

class String
{
public:
    String();
    String(const char* buf); //带参构造
    String(const String& other); //深拷贝

    int len()const; //获取字符串占用字节大小;
    char* c_str()const;//输出字符串;
    String& operator+(const String& other); //字符串拼接;
    char  at(int num)const;//按位置查找元素
    bool operator == (const String& other);//判断字符串是否相等;
    String operator =(const char* buf); //赋值



    char*  data; //存放数据的指针
    int datalen; //存放数据的个数
};

#endif

 

//cpp文件

#define  _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include "string.h"
using namespace  std;


//默认构造
String::String() 
{
    data = NULL;
    datalen = 0;
}

String::String(const char* buf) //带参构造
{
    this->data = new char[strlen(buf) + 1]; //动态申请对象
    strcpy(this->data, buf); //字符串拷贝操作
    this->datalen = strlen(buf);  //设置字符串的长度
}
//深拷贝
String::String(const String& other)
{
    this->data = new char(strlen(other.data) + 1);
    strcpy(this->data, other.data); //字符串拷贝操作
    this->datalen = other.datalen;  //设置字符串的长度

}



//获取字符串长度
int String::len()const 
{
    return datalen;
}

String& String::operator+(const String& other) //字符串拼接
{
    String* someone=new String;
    someone->data = new char[strlen(this->data) + strlen(other.data) + 1];
    strcpy(someone->data, this->data);
    strcat(someone->data, other.data);

    someone->datalen = this->datalen + other.datalen;
    return *someone;

}
//输出字符串;
char* String::c_str() const
{
    return this->data;
}

//按位置查找值
char String::at(int num) const
{
    char ch = this->data[num - 1];
    cout << "查找的位置的字符串的值为:" << this->data[num - 1] << endl;
    return ch;
}

//判断字符串是否相等;
bool String::operator == (const String& other)
{
    if (strcmp(this->data, other.data) == 0)
        return true;
    else
        return false;
}

//赋值并返回对象
String String::operator = (const char* buf) 
{
    if (this->data != NULL)
    {
        delete []this->data;
        this->data = NULL;
    }
    this->data = new char[strlen(buf) + 1];
    strcpy(this->data, buf);
    this->datalen = strlen(buf);
    return *this;
}

int main()
{
    String str1("hello");//初始化带参构造
    String str2("world");//初始化带参构造
    String* str3=new String(str1);//深拷贝
    int lenth=str1.len();//输出字符串长度
    cout << "str1的字符串长度为:" << lenth << endl;
    String str4 = str1 +str2; //字符串拼接
    cout<<"输出str1+str2拼接的字符串 :"<<str4.c_str()<<endl;//输出字符串
    char ch = str4.at(3); //查找字符串

    if (str1 == str2)
        cout << "str1和str2字符串相等" << endl;
    else
        cout << "str1和str2字符串不相等" << endl;


    String str5 = "123456";
    cout << "输出str5的数据 :" << str5.c_str() << endl;//输出字符串

    return 0;
}

 

posted @ 2020-04-21 01:31  神迹丶  阅读(376)  评论(0编辑  收藏  举报
网站已运行: