代码实现
#include <iostream>
#include <string.h>
using namespace std;
class my_string
{
private:
char *str;
int len;
public:
//无参构造
my_string(){}
//有参构造
my_string(char *q,int i)
{
str=new char[128];
strcpy(str,q);
len = i;
cout<<"this is a has parament constroctor"<<endl;
}
//拷贝构造
my_string(const my_string &O)
{
str=new char[128];
this->len = O.len;
strcpy(str,O.str);
}
//拷贝赋值
my_string& operator=(const my_string &O)
{
if(this!=&O)
{
len = O.len;
str = new char[128];
strcpy(str,O.str);
}
return *this;
}
//bool my_empty() 判空
bool my_empty()
{
if(my_size()==0)
return true;
else
{
cout<<str;
return false;
}
}
//int my_size() 求长度
int my_size()
{
int i=0;
while(*(str+i)!=0)
{
i++;
}
return i;
}
//转化为c风格字符串
char *my_str()
{
return str;
}
//关系运算符<
bool operator <(const my_string &R){
char *p=this->str;
char *q=R.str;
int n;
while(*p && *q && *p==*q){
p++;
q++;
}
n=*p-*q;
if(n<0)return true;
else return false;
}
//关系运算符>=
bool operator >=(const my_string &R){
char *p=this->str;
char *q=R.str;
int n;
while(*p && *q && *p==*q){
p++;
q++;
}
n=*p-*q;
if(n>=0)return true;
else return false;
}
//关系运算符<=
bool operator <=(const my_string &R){
char *p=this->str;
char *q=R.str;
int n;
while(*p && *q && *p==*q){
p++;
q++;
}
n=*p-*q;
if(n<=0)return true;
else return false;
}
//关系运算符==
bool operator ==(const my_string &R){
char *p=this->str;
char *q=R.str;
int n;
while(*p && *q && *p==*q){
p++;
q++;
}
n=*p-*q;
if(n==0)return true;
else return false;
}
//关系运算符!=
bool operator !=(const my_string &R){
char *p=this->str;
char *q=R.str;
int n;
while(*p && *q && *p==*q){
p++;
q++;
}
n=*p-*q;
if(n!=0)return true;
else return false;
}
//+运算符
my_string operator +(const my_string &R)const{
my_string temp;
strcat(temp.str,this->str);
strcat(temp.str,R.str);
temp.len=this->len+R.len;
return temp;
}
//取成员运算符
char operator [](const int n){
return this->str[n-1];
}
};
int main()
{
//验证有参构造
my_string str1("Hello World!",10);
cout<<"str1:"<<str1.my_str()<<endl;
my_string str2("h",10);
cout<<"str2:"<<str2.my_str()<<endl;
//验证拷贝构造
my_string str3=str1;
cout<<"str3"<<str3.my_str()<<endl;
//验证赋值构造
my_string str4;
//验证判空
my_string str5("",0);
if(str5.my_empty())
cout<<" no str5"<<endl;
else
cout<<"have str5"<<endl;
if(str4.my_empty())
cout<<"no str4"<<endl;
else
cout<<"have str4"<<endl;
//获取长度
int len=str1.my_size();
cout<<"the lenth of str1:"<<len<<endl;
cout << "Hello World!" << endl;
return 0;
}
运行结果
原文地址:https://www.jb51.cc/wenti/3280975.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。