在c ++中重载不同类型的比较运算符

时间:2014-04-17 20:23:11

标签: c++ operator-overloading comparison-operators

我需要能够将我的一个类(其中包含多于一个整数)与整数进行比较,即使这可能会延伸到相等的一点,但它足够接近......

如何为不同类型重载相等运算符?

我基本上有这样的课程

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;
}

3 个答案:

答案 0 :(得分:4)

为了澄清我的评论,这将支持代码,因此您可以提供运营商的所有变体:

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 ) ) {}

答案 1 :(得分:1)

是的,你需要定义三个operator ==,前提是你的类没有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 );
}

答案 2 :(得分:0)

是的,你需要两个运营商。

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作为参数)

相关问题