我们可以在C++重载“==”运算符来比较两个字符串吗?
Can we overload `==` operator in C++ to compare two strings?
如果我们想在不使用strcmp()
函数的情况下比较两个字符串,那么我们可以重载==
运算符来比较两个字符串吗?
我想你的意思是用 c 风格的字符串重载operator==
,那么答案是否定的。运算符重载应该用于自定义用户定义类型的操作数的运算符。
从标准来看,$13.5/6 重载运算符 [over.oper](强调我的)
运算符函数应为非静态成员函数或 是至少有一个参数的非成员函数,其类型为 类、对类的引用、枚举或对 枚举。
请注意,如果您的意思是std::string
,答案仍然是否定的。STL 提供了 operator==
的实现std::string
,您无法对其进行修改。实际上,您根本不需要重载它,只需使用它就可以了。
编辑
如果你想为自己的类重载它,那很好。如
Class X {
//...
};
bool operator==(const X& lhs, const X& rhs) {
// do the comparison and return the result
}
然后
X x1, x2;
//...
if (x1 == x2) {
//...
}
它不是已经超载了吗?
#include<iostream>
#include<cstring>
int main()
{
std::string a = "Ala";
std::string b = "Ala";
if(a==b)
std::cout<<"samen";
else
std::cout<<"but differentn";
}
上面的代码对我有用(代码块)
我有另一种解决方案可以让你少担心。我刚刚编写了函数equal(a,b)
告诉您两个字符串是否相同(随意复制所有代码并在终端中进行测试):
#include <iostream>
#include <string>
using namespace std;
//PRE: Two strings.
//POST: True if they are equal. False if they are different.
bool equal(const string& a, const string&b) {
int len_a = a.length();
int len_b = b.length();
if (len_a != len_b) return false;
//do this if they are equal
for (int i = 0; i < len_a; ++i) {
if (a[i] != b[i]) return false;
}
return true;
}
int main() {
string a, b;
cout << "Write two strings, with a space in between:" << endl;
cin >> a >> b;
if (equal(a,b)) cout << "they are equal" << endl;
else cout << "they are different" << endl;
}
相关文章:
- 两个字符串在 c++ 中不相等
- 在C++的两个字符串中连接以逗号分隔的唯一值
- 如何从文件中读取两个字符串和数字数组,并将它们存储在对象向量中
- 比较两个字符串后卡在无限循环中
- 我已经建立了递归关系,它找到了两个字符串之间最长的连续公共字符串,我怎么能跳过其中一个字符串中的一个字符
- 使用XOR查找O(n)-解决方案中的两个字符串是否为变位符
- 如何将两个字符串加在一起,就好像它们是变量一样?
- 我需要帮助在一个类中输入两个字符串并获取其输出
- 两个字符串之间的数学运算
- sscanf() 有两个字符串参数
- 我的字符串数组一次打印出前两个字符串
- 两个 c++ 字符串上的异或
- 函数返回两个字符串的第一个常用字符
- 目标是找到两个 c 字符串之间的公共前缀(必须使用特定的函数标头)
- 我需要在C++的两个字符串之间找到共同的前缀
- 我有一个返回字符串向量的函数.它需要两个字符串,并且返回一个字符串中缺少的字符串
- 给定两个字符串 S 和 T.确定与 T 相差最小的 S 子字符串?
- gtest:检查字符串是否等于两个字符串之一
- 交换两个字符串时访问正确的内存时,我遇到了分段错误
- 我可以在系统()中使用两个字符串吗?