定义一个字符串类,重载运算符,进一步修饰完善

 1 #define NULL 0
 2 #include <iostream>
 3 #include <string.h>
 4 /* run this program using the console pauser or add your own getch, system("pause") or input loop */
 5 using namespace std;
 6 class String
 7 {
 8     public:
 9         String(){
10             p=NULL;
11         }
12         String(char *str);
13         friend bool operator>(String &string1,String &string2);
14         friend bool operator<(String &string1,String &string2);
15         friend bool operator==(String &string1,String &string2);
16         void display();
17     private:
18         char *p;
19 };
20 
21 String::String(char *str)
22 {
23     p=str;
24 }
25 
26 void String::display()
27 {
28     cout<<p;
29 }
30 
31 bool operator>(String &string1,String &string2)
32 {
33     if(strcmp(string1.p,string2.p)>0)
34     return true;
35     else return false;
36 }
37 
38 bool operator<(String &string1,String &string2)
39 {
40     if(strcmp(string1.p,string2.p)<0)
41     return true;
42     else return false;
43 }
44 
45 bool operator==(String &string1,String &string2)
46 {
47     if(strcmp(string1.p,string2.p)==0)
48     return true;
49     else return false;
50 }
51 
52 void compare(String &string1,String &string2)
53 {
54     if(operator>(string1,string2)==1)
55     {
56         string1.display();
57         cout <<">";
58         string2.display();
59     }else if(operator<(string1,string2)==1)
60     {
61         string1.display();
62         cout <<"<";
63         string2.display();
64     }else if(operator==(string1,string2)==1)
65     {
66         string1.display();
67         cout <<"=";
68         string2.display();
69     }
70     cout<<endl;
71 }
72 int main(int argc, char** argv) {
73     String string1("Hello"),string2("Book"),string3("Computer"),string4("Hello");
74     compare(string1,string2);
75     compare(string2,string3);
76     compare(string1,string4);
77     return 0;
78 }

 

转载于:https://www.cnblogs.com/borter/p/9405397.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值