版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_20218109/article/details/52288104
#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