String类实现
Posted 蒲公英110
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
}
以上是关于String类实现的主要内容,如果未能解决你的问题,请参考以下文章