【问题标题】:Operator== to compare two different classesOperator== 比较两个不同的类
【发布时间】:2015-12-28 03:24:19
【问题描述】:

所以我有这两个类:FooBar

//forward declaration for Bar
class Bar;

typedef enum Type { TYPE1, TYPE2, TYPE3 };

// My class Foo
class Foo
{ 
public:
    explicit Foo(Type fooType) 
        :mType(fooType) 
    {} 

    Type getFooType() const
    {
        return mType;
    }

inline bool operator==(const Bar& bar) { return (bar.getBarType() == mType); } //ERROR: error C2027: use of undefined type 'Bar'

private:
    Type mType; 
};

// My class Bar
class Bar
{ 
public:
    explicit Bar(Type barType) 
        :mType(barType) 
    {} 

    Type getBarType() const
    {
        return mType;
    }

private:
    Type mType; 
};

现在,在我的代码中,我想比较两个实例(一个来自 Foo,另一个来自 Bar 类)。 像这样:

if(myBar->getBarType() == myFoo->getFooType())
{
 //...
}

问题: 我知道我需要实现 operator== 来允许这种比较。 所以我已经完成了如上所示...... 我得到了那个错误,尽管我已经做出了前向声明。 我在这里缺少什么让我可以在两个类上使用 operator== 进行比较?

【问题讨论】:

    标签: c++ operator-overloading


    【解决方案1】:

    您需要在Bar 类定义之后定义您的operator==,而不是在Foo 类中。在类中声明它,但在外面定义它。

    inline Foo::operator==(const Bar &bar) const { ... }
    

    这对您上面的测试没有太大帮助,因为左侧有 Bar 元素,右侧有 Foo,因此不会考虑 Foo 中的 operator==。定义对称全局 operator== 函数会很有用。

    inline bool operator==(const Bar &bar, const Foo &foo) { return foo == bar; }
    

    【讨论】:

    • 谢谢。但是按照您的建议使用对称全局运算符==,我收到错误:二进制“运算符==”参数太多。如何使用 2 个参数重载 operator==?
    • @waas1919 把它放在任何类之外
    【解决方案2】:

    你说你想让这个比较起作用......

    if(myBar->getBarType() == myFoo->getFooType())
    

    这是比较 getXType 函数返回的 enum Type 值,而不是 FooBar 对象本身,枚举默认情况下是可比较的,因此您无需提供自己的 operator==

    Never-the-less,你已经尝试过这样做,并且在...

    inline bool operator==(const Bar& bar) { return (bar.getBarType() == mType); } //ERROR: error C2027: use of undefined type 'Bar'
    

    ...问题是Bar 未在此函数定义出现在翻译单元中的位置定义。你可以只声明函数...

    inline bool operator==(const Bar& bar);
    

    ...然后在翻译单元中定义它,在class Bar的定义之后。

    这仍然只允许您在与作为左侧参数的 Foo 和右侧的 Bar 进行比较时省略显式的 getFooType() 调用。为了支持您要求的其他排序,您需要在 Bar 中使用与 const Foo& 一起使用的类似运算符。

    还有一个细节……你说……

    尽管我已经做出了前向声明,但我还是得到了那个错误。

    前向声明只是让编译器知道Bar 是一个类,它不会告诉编译器Bar 包含一个Type getBarType() 成员函数,并且需要这些知识来编译你的operator==

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-25
      • 1970-01-01
      • 2019-08-06
      • 2014-11-12
      • 2022-01-09
      • 2012-01-16
      相关资源
      最近更新 更多