实验课程任务:
需求:
3、仿照标准字符串类string,设计一个自己的字符串类String。
主要完成以下任务:
1)数据成员是字符指针,可自动适应不同的串长度。
2)串复制,既可使用字符串常量进行复制,也可以使用其他的字符串对象进行复制。
3)串赋值。既可赋值为字符串常量,也可以赋值为使用其他的字符串对象。
4)串连接。重载“+”和“+=”。
5)重载下标运算符[]。
6)串比较。重载 “==”和“<”。
7)字符串输入和输出。重载“>>”和“<<”。
代码实现:
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstring>
using namespace std;
class String {
public:
String(const char* p_c = "");
String(const String& s);
~String() {};
String& operator = (const char* p_c);
String& operator = (const String& s);
String& operator + (const String& s);
String& operator += (const String& s);
char& operator [] (int i);
bool operator == (const String& s);
bool operator < (const String& s);
friend ostream& operator << (ostream& out, const String& s);
friend istream& operator >> (istream& in, const String& s);
int Length()const { return strlen(p); }
private:
char* p;
};
//构造函数
String::String(const char* p_c)
{
p = new char[strlen(p_c) + 1];
strcpy(p, p_c);
}
String::String(const String& s)
{
p = new char[strlen(s.p) + 1];
strcpy(p, s.p); //深拷贝
}
//重载赋值1
String& String::operator = (const char* p_c)
{
if (p != p_c) //不是自己
{
delete []p;
p = new char[strlen(p_c) + 1];
strcpy(p, p_c);
}
return *this;
}
//重载赋值2
String& String::operator = (const String& s)
{
if (p != s.p)
{
delete []p;
p = new char[strlen(s.p) + 1];
strcpy(p, s.p);
}
return *this;
}
//串连接1
String& String::operator + (const String& s)
{
char* p_temp = new char[strlen(p) + strlen(s.p) + 1]; //临时空间
strcpy(p_temp, p);
strcat(p_temp, s.p); //拼接
delete[]p;
p = p_temp;
return *this;
}
//串连接2
String& String::operator += (const String& s)
{
*this = *this + s; //复用
return *this;
}
//串比较
bool String::operator == (const String& s)
{
return strcmp(p, s.p) == 0;
}
bool String::operator < (const String& s)
{
return strcmp(p, s.p) < 0;
}
//重载[]运算符
char& String::operator [] (int i)
{
return p[i];
}
ostream& operator << (ostream& out, const String& s)
{
out << s.p;
return out;
}
istream& operator >> (istream& in, const String& s)
{
in >> s.p;
return in;
}
//测试部分
void test01()
{
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;
}
int main()
{
test01();
return 0;
}
初学者能力有限,欢迎大佬指点,虚心接受!