[英]Overloading comparison operators for different types in c++
我需要能够将我的一个类(其中包含多于一个整数)与整数进行比较,即使这可能会延伸到相等的一点,但它足够接近......
如何为不同类型重载相等运算符?
我基本上有这样一个班级
struct MyClass {
int start;
int middle;
int threequarters;
};
和重载的运算符
inline bool operator==(const MyClass& lhs, const MyClass& rhs) {
return lhs.middle == rhs.middle;
}
因此,当与整数比较时,我需要与中间变量进行比较,但我不确定我是否需要两组运算符函数,一个是整数是lhs还是一个整数是rhs?
inline bool operator==(const int& lhs, const MyClass& rhs) {
return lhs == rhs.middle;
}
inline bool operator==(const MyClass& lhs, const int& rhs) {
return lhs.middle == rhs;
}
为了澄清我的评论,这将支持代码,因此您可以提供所有运算符的变体:
inline bool operator==(const MyClass& lhs, const MyClass& rhs) {
return lhs.middle == rhs.middle;
}
inline bool operator==(const int& lhs, const MyClass& rhs) {
return lhs == rhs.middle;
}
inline bool operator==(const MyClass& lhs, const int& rhs) {
return lhs.middle == rhs;
}
并为每个运营商(这会吞噬大量代码)做到这一点。 或者,如果它有意义,你可以提供一个构造函数,从int构造:
struct MyClass {
MyClass() {} // default
MyClass( int x ) { /* init for an int here */ }
int start;
int middle;
int threequarters;
};
如果这样做,那么每个运算符只需要MyClass,MyClass版本:
inline bool operator==(const MyClass& lhs, const MyClass& rhs) {
return lhs.middle == rhs.middle;
}
因为当编译器看到:
if ( 5 == my_class ) {}
它实际上是这样的:
if ( MyClass(5).operator==( my_class ) ) {}
是的,您需要定义三个运算符==,前提是您的类没有类型为int的对象的转换构造函数。
inline bool operator==(const MyClass& lhs, const MyClass& rhs) {
return lhs.middle == rhs.middle;
}
inline bool operator==(const MyClass& lhs, int rhs) {
return lhs.middle == rhs;
}
inline bool operator==(int lhs, const MyClass& rhs) {
return operator ==( rhs, lhs );
}
是的,你需要两个运营商。
bool operator==(const A& a, const int & b)
{
return a.value == b;
};
如果只定义了上面的运算符,编译器将抛出一个错误,如果您尝试以下操作,则无法进行转换: 2 == a
(考虑到类A没有将整数作为参数的隐式构造函数)
对于每个二进制操作,编译器尝试执行隐式转换以适合操作。 例如,如果class A
具有operator int
定义,则不需要运算符,因为编译器会隐式地将A
类型转换为整数,然后执行bool operator==(int,int)
运算。 如果没有定义运算符,那么编译器会抛出一个错误,说没有可用的转换(即,没有运算符==在左侧或右侧接受A作为参数)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.