首页 > 其他 > 详细

String类实现

时间:2016-11-12 23:29:26      阅读:449      评论:0      收藏:0      [点我收藏+]

String类是应用框架中不可或缺的类
重载运算符实现字符串的操作

#idndef IOTECK_STRING_H_
#define IOTECK_STRING_H_
namespace iotek
{
class String
{
public:
String(const char*=NULL);
~String();
String(const String&); //拷贝构造函数
//String a; a=b;
String& operator=(const String &); //赋值运算符
//String a; a="hello";
String& operator=(const char*);

String& operator+=(const String&);
String operator+(const String&)const;

String& operator+=(const char*);
String operator+(const char*)const;


inline const char* data() const
{
return m_data;
}
private:
char *m_data;
}
}
#endif

.CPP文件

#include"iotekstring.h"
#include<iostream>
#include<string.h>
using namespace std;
using namespace iotek;
String::String(const char *str)
{
if(NULL==str)
{
m_data=new char[1];
*m_data=‘\0‘;
}
else{
int length=strlen(str);
m_data=new char[length+1];
strcpy(m_data,str);
}
}

String::~String()
{
delete [] m_data;
}

String::String(const String &other)
{
int length=strlen(other.m_data);
m_data=new char[length+1];
strcpy(m_data,other.m_data);
}

String& String::operator=(const String &other)
{
if(this==&other)
return *this;
delete [] m_data;
int length=strlen(other.m_data);
m_data=new char[length+1];
strcpy(m_data,other.m_data);
return *this;
}

String& String::operator=(const char *other)
{
delete[] m_data;
if(other==NULL)
{
m_data=new char[1];
*m_data=‘\0‘;
}
else
{
int length=strlen(other);
m_data=new char[length+1];
strcpy(m_data,other);
}
return *this;
}

String& String::operator+=(const String& other)
{
char* tmp=m_data;
int length=strlen(m_data)+strlen(other.m_data);
m_data=new char[length+1];
strcpy(m_data,tmp);
strcat(m_data,other.m_data);
delete [] tmp;

return *this;
}

String String::operator+(const String& other)const
{
String result;
result+=*this;
result+=other;
return result;
}

String& String::operator+=(const char* other)
{
String tmp(other);
*this+=tmp;

return *this;
}

String String::operator+(const char* other)const
{
String result=*this;
result+=other;

result result;
}
main.cpp


#include"iotekstring.h"
#include<iostream>
#include<string.h>
using namespace std;
using namespace iotek;

int main(int argc,const char *argv[])
{
String s1("hello");
String s2=s1;
String s3="world";

s1+=s3;

s3+="!";

String s4=s1+s2;
s4=s1+"hello";

system("pause");
return 0;
}

 

String类实现

原文:http://www.cnblogs.com/zsq1993/p/6057610.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!