题目描述
定义一个字符串类str,用来存放不定长的字符串,重载运算符"= ="、"<"、">",用于两个字符窜的等于、小于和大于的比较运算。
要求如下:
1.实现str类;
2.编写main函数,初始化三个str对象A、B、C,然后用这三个对象去测试重载的运算符。如果A>B,则输出A的字符串;否则输出B的字符串。如果A<C,则输出A的字符串;否则输出C的字符串。如果B==C,则输出B的字符串;否则输出C的字符串。
输入
输入3行,每行为一个字符串,初始化三个str对象。
输出
输出比较之后的结果字符串,每个比较的结果一行。
IO模式
本题IO模式为标准输入/输出(Standard IO),你需要从标准输入流中读入数据,并将答案输出至标准输出流中。
输入样例1
i am a student\n
i love China\n
i love China
输出样例1
i love China\n
i am a student\n
i love China
AC代码
#include<iostream>
#include<cstring>
using namespace std;
class str {
char* p;
public:
str():p(NULL) {}
str(char* s) { p = s; }
friend bool operator>(str& s1, str& s2);
friend bool operator<(str& s1, str& s2);
friend bool operator==(str& s1, str& s2);
void show() {
cout << p;
}
};
bool operator>(str& s1, str& s2) {
if (strcmp(s1.p, s2.p) > 0)return true;
else return false;
}
bool operator<(str& s1, str& s2) {
if (strcmp(s1.p, s2.p)<0)return true;
else return false;
}
bool operator==(str& s1, str& s2) {
if (strcmp(s1.p, s2.p) == 0)return true;
else return false;
}
int main() {
char s1[100], s2[100], s3[100];
cin.getline(s1, 100);
//cin.ignore();
cin.getline(s2, 100);
//cin.ignore();
cin.getline(s3, 100);
str A(s1);
str B(s2);
str C(s3);
if (A > B)A.show();
else B.show();
cout << endl;
if (A < C)A.show();
else C.show();
cout << endl;
if (B == C)B.show();
else C.show();
cout << endl;
return 0;
}