重载String:Overload String
来源:互联网 发布:小米电视 广告 知乎 编辑:程序博客网 时间:2024/05/16 10:50
#include "stdafx.h"
#include <iostream>
#include <stdlib.h>
using namespace std;
class String
{
private:
char* ch;
int size;
public:
String(char *s="");
String(const String &s);
~String(void);
int length(void)const;
String sub(int pos,int len);
String& operator=(const String &s);
String& operator=(char *s);
bool operator==(const String& s)const;
bool operator==(char *s)const;
friend bool operator==(char *ch,const String& s);
};
String::String(char *s )
{
size=strlen(s)+1;
ch=new char[size];
strcpy(ch,s);
}
String::String(const String& s)
{
size=s.size;
ch=new char[size];
if(ch==NULL) exit(0);
for(int i=0;i<size;i++)
{
ch[i]=s.ch[i];
}
}
int String::length(void)const
{
return size;
}
String::~String(void)
{
delete []ch;
}
String String::sub(int pos,int len)
{
int subsize=size-pos-1;
String temp;
char *p,*q;
if(subsize<=0)
return temp;
if(len>subsize)
len=subsize;
delete []temp.ch;
temp.ch=new char[len+1];
p=temp.ch;
q=&ch[pos];
for(int i=0;i<len;i++)
*p++=*q++;
*p=NULL;
temp.size=len+1;
return temp;
}
String& String::operator =(const String &s)
{
if(s.size!=size)
{
delete []ch;
ch=new char[s.size];
size=s.size;
}
for(int i=0;i<size;i++)
ch[i]=s.ch[i];
return *this;
}
String& String::operator=(char *s)
{
int len=strlen(s);
if(size!=len+1)
{
delete[]ch;
ch=new char[size];
size=len+1;
}
strcpy(ch,s);
return *this;
}
bool String::operator==(const String& s)const
{
return(strcmp(ch,s.ch)==0);
}
bool String::operator==(char* s)const
{
return (strcmp(ch,s)==0);
}
bool operator==(char *ch,const String& s)
{
return (strcmp(ch,s.ch)==0);
}
int _tmain(int argc, _TCHAR* argv[])
{
String s1("data structure");
String s2("structure");
String s3;
s3=s1.sub(5,9);
char *my="structure";
if(s3==s2)
cout<<"good"<<endl;
if(s2==my)
cout<<"very good"<<endl;
if(my==s2)
cout<<"very very good"<<endl;
return 0;
}
- 重载String:Overload String
- String 重载"+"
- String运算符重载
- 重载 overload
- 重载(Overload)
- string重载和类型转换
- c++ string 函数的重载
- string
- String
- String
- string
- string
- String
- string
- String
- string
- string
- string
- 重载操作符:Array:Overload Operator
- 连接数量满导致数据库连接不上问题
- kksfbc child completion事件导致cpu长时间不释放
- 吸血鬼数字 高效算法
- 空间插值方法总结
- 重载String:Overload String
- 视图的理解
- IE8下eWebEditor编辑器无法使用的解决方法
- 纪念
- Microsoft Visual Studio 2008单元测试入门
- 关于checkboxlist前台取值问题
- 构造堆栈:Private List Can Be Converted To Stacklist
- 通过GET方法来发送数据时不能直接使用变量分隔符
- Fat jar 非常不错的打包插件