蒲公英110

String类实现

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;
}

 

posted on 2016-11-12 21:30  蒲公英110  阅读(278)  评论(0编辑  收藏  举报

导航