我们可以在C++重载“==”运算符来比较两个字符串吗?

Can we overload `==` operator in C++ to compare two strings?

本文关键字:两个 字符串 比较 运算符 C++ 重载 我们      更新时间:2023-10-16

如果我们想在不使用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;
}