#include<iostream>
#include<string>
using namespace std;
//重载运算符<,>,==
class str
{
public:
str(){} //默认构造函数
str(string q);
friend bool operator<(str &str1,str &str2); //友元函数
friend bool operator>(str &str1,str &str2);
friend bool operator==(str &str1,str &str2);
private:
string p;
};
str::str(string q)
{
p=q;
}
bool operator>(str &str1,str &str2)
{
if(str1.p>str2.p) return true;
else return false;
}
bool operator<(str &str1,str &str2)
{
if(str1.p<str2.p) return true;
else return false;
}
bool operator==(str &str1,str &str2)
{
if(str1.p==str2.p) return true;
else return false;
}
int main()
{
str str1("hello");
str str2("hello");
bool compare;
compare=str1<str2;
cout<<boolalpha<<"str1<str2 is "<<compare<<endl;
compare=str1>str2;
cout<<boolalpha<<"str1>str2 is "<<compare<<endl;
compare=str1==str2;
cout<<boolalpha<<"str1==str2 is "<<compare<<endl;
return 0;
}
C++重载运算符大于小于等于实现字符串比较(string类),C风格字符串稍微改一下就好
最新推荐文章于 2025-10-10 13:37:29 发布
本文介绍了一个使用C++实现的字符串类,通过重载比较运算符<、>和==来实现字符串之间的比较。示例中定义了一个名为str的类,其内部包含了一个string类型的成员变量,并提供了相应的构造函数。通过友元函数的形式实现了三个运算符的重载,使得可以方便地比较两个str对象的内容。
1177

被折叠的 条评论
为什么被折叠?



