设计字符串类 myString,若有 myString 类对象 s1、s2 和 s3,重载运算符实现如下操作:
1)重载“+”实现字符串连接功能,使表达式 s1= s2+s3 成立;
2)重载“<”判断两个字符串的大小,如 if(s1 < s2) cout<<s1<<”<”<<s2;
3)重载“<<”与“>>”,实现字符串的输入与输出操作,如 cin>>s2; cout<<s2<<endl;
4)重载运算符“()”,从字符串对象中返回一个子串。如 s1(2,4)表示返回从子串,即从
s[2](s1 第 3 个字符)开始的子串(包括 s1[2]、s1[3]和 s1[4]三个字符)。
5)重载运算符[],获取下标为 i 的字符,并可以执行对该字符赋值的操作;
6) 重载运算符=,实现字符串对象的赋值操作。
#include <iostream>
#include<cstring>
using namespace std;
class myString
{
public:
myString(int size, const char*);
myString();
~myString();
myString(const myString&);
myString operator+(myString&);
bool operator<(myString&);
friend ostream& operator<<(ostream&, const myString&);
friend istream& operator>>(istream&, myString&);
myString operator()(int, int);
myString& operator[](int);
myString& operator=(const myString&);
private:
int length;
char* s;
};
myString::myString(int size, const char* s1) :length(size)
{
s = new char[length + 1]();
strcpy(s, s1);
}
myString::myString()
{
length = 0;
s = new char[length + 1]();
}
myString::~myString()
{
delete[]s;
s = nullptr;
}
myString::myString(const myString&s1) {
length = s1.length;
s = new char[length + 1]();
strcpy(s, s1.s);
}
myString myString::operator+(myString& s1) {
myString S(length + s1.length, s);
strcat(S.s, s1.s);
return S;
}
bool myString::operator<(myString& s1) {
if (strcmp(s, s1.s) >= 0)
{
return false;
}
else
{
return true;
}
}
ostream& operator<<(ostream& os, const myString& s1) {
os << s1.s << endl;
return os;
}
istream& operator>>(istream& is, myString& s1) {
cout << "length:";
is >> s1.length;
if (s1.s!=NULL)
{
delete[]s1.s;
}
s1.s = new char[s1.length+1]();
cout << "string:";
is >> s1.s;
return is;
}
myString myString::operator()(int j, int k) {
myString s1(k - j + 1, "");
for (int i = 0; i < k - j + 1; i++)
{
s1.s[i] = s[j + i];
}
return s1;
}
myString& myString::operator[](int i) {
cout << "You are goning to change it as:" << endl;
cin >> s[i];
return *this;
}
myString& myString::operator=(const myString& s1) {
length = s1.length;
if (s!=NULL)
{
delete[]s;
}
s = new char[length + 1];
strcpy(s, s1.s);
return*this;
}
int main()
{
myString s1(5, "zhang"), s2(2, "li"), s3;
cin >> s3;
cout << s3;
cout << s1 << s2 << s3;
s3 = s1 + s2;
cout << s3;
if (s1 < s2)
{
cout << s1 << "<" << s2;
}
myString s5 = s1(2, 4);
cout << s5;
cout << s2[1];
return 0;
}