在本文中我们自己将自己定义并测试c++中的string类。
实现代码如下:
#pragma once
//String.h
#include<iostream>
using namespace std;
#pragma warning(disable:4996)
class String {
private:
char* str;
int size;
public:
String();
String(const char* p);
String(String& p);
~String();
int Length();
String& operator=(const String& p);
String operator+(const String& p);
String& operator+=(const String& p);
char& operator[](int i);
bool operator==(const String& p);
bool operator<(const String& p);
String operator=(const char* p);
friend ostream& operator<<(ostream& out,String& p);
friend istream& operator>>(istream& in,String& p);
};
String::String() {
size = 0;
str = new char[1];
str[0] = '\0';
}
String::String(const char* p) {
size = strlen(p);
str = new char[size + 1];
strcpy_s(str,size+1, p);
}
String::String(String& p) {
size = p.size;
str = new char[size + 1];
strcpy_s(str, size+1, p.str);
}
String::~String() {
if (str != NULL) {
delete[] str;
str = NULL;
size = 0;
}
}
int String::Length() {
return size;
}
String String::operator+(const String& p)
{
String a;
a.size = size + p.size;
delete[]a.str;
a.str = new char[a.size + 1];
memset(a.str, 0, a.size);
strcat_s(a.str, size+1, str);
cout << a << endl;
strcat_s(a.str,a.size+1, p.str);
cout << a << endl;
cout << a << endl;
return a;
}
String& String::operator+=(const String& p) {
*this = *this + p;
return *this;
}
char& String::operator[](int i) {
if (i >= size)
{
cout << "索引超过最大值" << endl;
return str[0];
}
return str[i];
}
bool String::operator==(const String& p) {
return !strcmp(str, p.str);
}
bool String::operator<(const String& p) {
if (size < p.size)return true;
else return false;
}
String String::operator=(const char* p) {
size = strlen(p);
str = new char[size + 1];
strcpy_s(str, size + 1, p);
return *this;
}
ostream& operator<<(ostream& out,String& p) {
out << p.str;
return out;
}
istream& operator>>(istream& in, String& p) {
in >> p.str;
const char* tem = p.str;
p.size = strlen(tem);
p.str = new char[p.size + 1];
strcpy(p.str, tem);
return in;
}
String& String::operator=(const String& p)
{
if (this != &p)
{
size = p.size;
str = new char[size + 1];
strcpy(str, p.str);
}
return *this;
}
测试代码如下:
#include"String.h"
int main() {
String s1("Help!"), s2("Good!"), s3(s2), s4, s5;
cout << "s1=" << s1 <<endl;
s3 = "Hello!";
cout << "s3=" << s3 << endl;
s3 = s2;
cout << "s3=" << s3 << endl;
s3 +=s2;
cout << "s3=" << s3 << endl;
cin >> s4;
cout << "s4=" << s4 << endl;
s5 = s3 + s4;
cout << "s5=" << s5 << endl;
s5[0] = 'g';
cout << "s5=" << s5 << endl;
cout << "strlen(s5)=" << s5.Length() << endl;
cout << boolalpha << (s3 == s1) << endl;
cout << boolalpha << (s3 < s1) << endl;
return 0;
}