您的位置:首页 > 编程语言 > C语言/C++

C++ 基于类的String实现

2016-08-07 00:10 232 查看

STL中string字符串类有很多成员函数,在此文中,小编根据在学的数据结构写了一个简单的String类,基本函数功能与标准模板库的函数有所雷同。亮点在于将list单向链表转化成String对象进项String的操作。在写比较函数时可以充分利用C字符串转换函数将String对象的比较转换成C字符串的比较,简化了代码的书写。

代码如下:

/////// the achievement of class string///////////
#include <iostream>
#include <list>
#include <cstring>
#include "List.h"
using namespace std;
class String {
public:
String();
~String();
String(const String& copy);
String( const char* copy);
String(List<char>& copy);
void operator=(const String& copy);
const char* c_str() const;
protected:
char* entries;
int length;

};

bool operator == (const String &first, const String& second);
bool operator > ( const String &first, const String& second);
bool operator < ( const String &first, const String& second);
bool operator >= (const String &first, const String& second);
bool operator <= (const String &first, const String& second);
bool operator != (const String &first, const String& second);
String::String() {
entries = NULL;
length = 0;
}
String::String(const char* in_string) {
length = strlen(in_string);
entries = new char[length + 1];
strcpy(entries, in_string);
}

String::~String() {
delete entries;
}

String::String(const String& copy) {
length = copy.length;
entries = new char[copy.length+1];
int i;
for( i = 0; i < length; i++) entries[i] = copy.entries[i];
entries[i] = '\0';

}

String::String(List<char>& in_list) {
length = in_list.length();
entries = new char[length+1];
for( int i = 0; i < length; i++)  entries[i] = in_list.getItem(i);
entries[length] = '\0';
}

void String::operator=(const String& copy) {
int i;
if(entries != NULL) delete entries;
length = copy.length;
entries = new char[copy.length+1];
for(i = 0; i < copy.length; i++) entries[i] = copy.entries[i];
entries[i] = '\0';

}
const char* String::c_str() const {
return (const char*) entries;
}

bool operator==(const String& first, const String &second) {
return strcmp(first.c_str(), second.c_str() ) == 0;
}

bool operator > ( const String &first, const String& second) {
return strcmp(first.c_str(), second.c_str()) > 0;
}

bool operator < ( const String &first, const String& second) {
return strcmp(first.c_str(), second.c_str()) < 0;
}

bool operator >= ( const String &first, const String& second) {
return strcmp(first.c_str(), second.c_str()) >= 0;
}

bool operator <= (const String& first, const String& second) {
return strcmp(first.c_str(), second.c_str()) <= 0;
}

bool operator != (const String& first, const String& second) {
return strcmp(first.c_str(), second.c_str()) != 0;
}

int main() {
String str1 =  "I'm a student studying in sun yatsen univesity";
String str2(str1);
if( str1 == str2) cout<< "str1 == str2" <<endl;
if( str1 > str2) cout << "str1 > str2" <<endl;
}


写完之后,小编只测试了编译和个别函数。如果BUG发现,还望批评指出,不吝赐教。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: