简体   繁体   English

我如何定义一个运算符重载函数来比较来自两个不同类的两个对象?

[英]how can i define an operator overloading function to compare two objects from two different classes?

I know how to define operator overloading function for two objects from the same class, but I search everywhere on the net or other topics in StackOverflow and I didn't get the correct answer.我知道如何为来自同一个类的两个对象定义运算符重载函数,但是我在网上到处搜索或在 StackOverflow 中的其他主题中搜索,但没有得到正确的答案。

I need a simple example to add or compare to objects from different classes.我需要一个简单的例子来添加或比较来自不同类的对象。 I don't know if I want to define the operator overloading outside the classes, should I make that the friends of two classes or something else.我不知道我是否想在类之外定义运算符重载,我应该让它成为两个类的朋友还是其他什么。

This is a good case for using free operators.这是使用自由运算符的好例子。

bool operator==(TypeA const & a, TypeB const & b) {
  // Do comparison
}

bool operator!=(TypeA const & a, TypeB const & b) {
  return !(a == b);
}

bool operator==(TypeB const & b, TypeA const & a) {
  return a == b;
}

bool operator!=(TypeB const & b, TypeA const & a) {
  return a != b;
}

You should only make them friends of the revelant types if it is necessary;如果有必要,你应该只让他们成为相关类型的朋友; if the state can be fully observed from public members, there is no need to make them friends.如果国家可以从公众成员那里得到充分的观察,就没有必要和他们做朋友。


There is an alternative approach, however: if values of these types can be considered equal, that implies that one could be converted to the other.但是,还有一种替代方法:如果可以认为这些类型的值相等,则意味着可以将其转换为另一种。 If that is the case, they could be compared after conversion:如果是这种情况,可以在转换后进行比较:

TypeA a{createTypeA()};
TypeB b{createTypeB()};

bool result = a == TypeA{b};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM