本文主要是介绍C++重载运算符大于小于等于实现字符串比较(string类),C风格字符串稍微改一下就好,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
#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风格字符串稍微改一下就好的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!