gpt4 book ai didi

c++ - 我们可以在 C++ 中重载 `==` 运算符来比较两个字符串吗?

转载 作者:太空狗 更新时间:2023-10-29 19:47:59 27 4
gpt4 key购买 nike

如果我们想在不使用strcmp() 函数的情况下比较两个字符串,那么我们是否可以重载== 运算符来比较两个字符串?

最佳答案

我想你打算用 c 风格的字符串重载 operator==,那么答案是operator overloading应该用于为用户定义类型 的操作数自定义运算符。

从标准开始,$13.5/6 重载运算符 [over.oper](强调我的)

An operator function shall either be a non-static member function or be a non-member function that has at least one parameter whose type is a class, a reference to a class, an enumeration, or a reference to an enumeration.

注意你的意思是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) {
//...
}

关于c++ - 我们可以在 C++ 中重载 `==` 运算符来比较两个字符串吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37385401/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com