大橙子网站建设,新征程启航
为企业提供网站建设、域名注册、服务器等服务
使用C++ 实现string类
创新互联服务电话:18982081108,为您提供成都网站建设网页设计及定制高端网站建设服务,创新互联网页制作领域十余年,包括成都茶艺设计等多个行业拥有多年设计经验,选择创新互联,为网站锦上添花。重载运算符 = += == != >><<
#include#include#includeusing namespace std;
class myString{
private:
char *_str;
public:
myString(const char *s){
if(s!=NULL){
_str = new char[strlen(s)+1];
strcpy(_str,s);
}
}
myString(const char c){
_str = new char[2];
_str[0] = c;
_str[1] = '\0';
}
myString(){
_str = nullptr;
}
myString(const myString &s){
char *p = _str;
_str = new char[strlen(s._str)+1];
if(p!=nullptr){
delete p;
}
strcpy(_str,s._str);
}
~myString(){
delete _str;
}
bool operator==(myString const&str1)const{
return strcmp(this->_str,str1._str)==0;
}
bool operator!=(myString const&str1)const{
return !(strcmp(this->_str,str1._str)==0);
}
myString &operator=(myString const&str1){
if(strlen(this->_str)>=strlen(str1._str)){
strcpy(this->_str,str1._str);
}else{
char *p = new char[strlen(str1._str)+1];
char *q = this->_str;
strcpy(p,str1._str);
this->_str = p;
if(q!=nullptr){
delete q;
}
}
return *this;
};
myString &operator=(char const*str1){
if(_str && strlen(this->_str)>=strlen(str1)){
strcpy(this->_str,str1);
}else{
char *p = new char[strlen(str1)+1];
char *q = this->_str;
strcpy(p,str1);
this->_str = p;
if(q!=nullptr){
delete q;
}
}
return *this;
};
friend ostream &operator<< (ostream &os,myString const &str1){
os<>(istream &is,myString &str1){
char *p = new char[1024];
is>>p;
str1=p;
return is;
}
myString operator+(myString const&str1)const{
myString mystr;
mystr._str = new char[strlen(this->_str)+strlen(str1._str)+1];
strcpy(mystr._str,this->_str);
strcat(mystr._str,str1._str);
return mystr;
};
myString &operator+=(myString const&str1){
char *p = new char[strlen(str1._str)+strlen(this->_str)+1];
char *q = this->_str;
strcpy(p,this->_str);
strcat(p,str1._str);
this->_str = p;
if(q!=nullptr){
delete q;
}
return *this;
};
myString &operator+=(const char *str1){
char *p = new char[strlen(str1)+strlen(this->_str)+1];
char *q = this->_str;
strcpy(p,this->_str);
strcat(p,str1);
this->_str = p;
if(q!=nullptr){
delete q;
}
return *this;
};
myString &operator+=(const char str1){
assert(str1);
char *p = new char[strlen(this->_str)+2];
char *q = this->_str;
strcpy(p,this->_str);
p[strlen(this->_str)+1] = str1;
p[strlen(this->_str)+1] = '\0';
this->_str = p;
if(q!=nullptr){
delete q;
}
return *this;
};
};
int main(){
myString s1("hello");
myString s2 = "world";
myString s3;
s3 = "world";
cout<>s1;
cout<
[~/Class/C++/day4]->./a.out
hello
world
world
helloworld
0
1
helloworld
helloworld
nihao
nihao
你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧