==重载返回表达式 [英] == Overloading return expression

查看:63
本文介绍了==重载返回表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是搜索程序中的一小段代码.我对此有一个疑问.
x.the_key的作用是什么?为什么在这里不能用x==y检查x和y?
为什么我们要对键值进行本地复制?

Here''s a short snippet from a search program. I had one doubt about this.
What is x.the_key is being used for? Why can''t x and y be checked with x==y here?
Why do we have to the local copy of a key''s value?

class Key()
{
public: Key(int x=0);
int the_key()const;
}
bool operator == (const Key &x, const Key &y) // == overloading
{
return x.the_key()==y.the_key(); // x.the_key?
}

推荐答案

通过==比较两个对象与比较这些对象的内容有所不同.由于您仅向我们显示了Key类的合同,而不是其实现,因此我只能猜测函数int the_key()返回存储在类Key中的整数值. 重载==运算符已在此处完成,因此您可以像通常将两个引用与各自实例进行比较一样,比较两个类型为Key的实例的内容.
注意!:更改==运算符的语义被认为是错误的设计!除非您有充分的理由,否则请不要这样做.

乍一看,人们会认为正在比较两个引用,但是通过重载==运算符,现在可以比较它们的内容.
完成此操作必须有一个非常非常好的理由,并且应该对其进行很好的记录.

最好的问候,

曼弗雷德(Manfred)
Comparing two objects via == is something different from comparing the content of these objects. Since you have shown us only the contract for class Key and not its implementation, I can only guess that the function int the_key() returns the integer value that is stored inside class Key.
Overloading the == operator is done here so you can compare the content of two instances of type Key as you would usually compare the two references to the respective instances.

Caveat!: Changing the semantic of the == operator is considered bad design! Please don''t do that unless you have a very good reason.

At an superficial glance one would think that two references are being compared, but by overloading the == operator it is now a comparison of their content.
There must be a very, very good reason when this is done and it should be documented really well.

Best Regards,

Manfred


这篇关于==重载返回表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆