Mystring

本文介绍了一个简单的自定义String类的实现过程,包括构造函数、拷贝构造函数、赋值运算符重载、下标运算符重载等功能,并演示了如何使用这个自定义String类。

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

#ifndef __MYSTRING_H__
#define __MYSTRING_H__
#include <string.h>
#include <malloc.h>
class String{
private:
	char *str;
public:
	String(const char *str);
	String(const String& string);
	bool operator==(const String& str);
	String& operator=(const String& str);
	char& operator[](int i);
	char *string();
	~String();
	const char* GetChar()const;
};


#endif



#include "mystring.h"

String::String(const char *str)
{
	int len=strlen(str);
	this->str=(char*)malloc(0);
	this->str=(char*)realloc(this->str,len);
	strcpy(this->str,str);
}
String::String(const String& string)
{
	int len=strlen(string.GetChar());
	this->str=(char*)malloc(0);
	this->str=(char*)realloc(this->str,len);
	strcpy(this->str,string.GetChar());
}
char* String::string()
{
	return this->str;
}

String::~String()
{
	free(this->str);
}

bool String::operator==(const String& str)
{
	int len1=strlen(this->str);
	int len2=strlen(str.GetChar());
	if(len1!=len2){
		return false;
	}
	for(int i=0;i<len1;++i){
		if(*(str.GetChar()+i)!=*(this->str+i)){
			return false;
		}
	}
	return true;
}

const char* String::GetChar()const
{
	return this->str;
}

char& String::operator[](int i)
{
	return *(this->str+i);
}

String& String::operator=(const String& str)
{
	strcpy(this->str,str.GetChar());
	return *this;
}


#include "mystring.h"
#include <iostream>
using namespace std;

int main(void)
{
	String string("asfdfdfd");
	String string1("454545");
	String string2(string1);
	cout<<"string: "<<string.string()<<endl;
	cout<<"string1: "<<string1.string()<<endl;
	cout<<"string2: "<<string2.string()<<endl;
	cout<<"string==string1: "<<(string==string1)<<endl;
	cout<<"string[0]: "<<string[0]<<endl;
	string=string1;
	cout<<"string: "<<string.string()<<endl;
	
	return 0;
}

运行结果

string: asfdfdfd
string1: 454545
string2: 454545
string==string1: 0
string[0]: a
string: 454545



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值