加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 10:13:01 所属栏目:百科 来源:网络整理
导读:如果我们想在不使用strcmp()函数的情况下比较两个字符串,那么我们可以重载==运算符来比较两个字符串吗? 解决方法 我想你的意思是用c风格的字符串重载operator ==,然后答案是否定的. operator overloading应该用于为用户定义类型的操作数定制运算符. 从标准,
如果我们想在不使用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为std :: string提供了operator==的实现,您无法修改它.事实上,你根本不需要重载它,只需使用它就可以了.

编辑

如果你想为自己的班级重载它,那很好.如

Class X {
    //...
};
bool operator==(const X& lhs,const X& rhs) { 
    // do the comparison and return the result
}

然后

X x1,x2;
//...
if (x1 == x2) {
    //...
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读