gpt4 book ai didi

c++ - 运算符==比较两个不同的类

转载 作者:行者123 更新时间:2023-11-28 02:14:21 25 4
gpt4 key购买 nike

所以我有这两个类: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== 进行比较?

最佳答案

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

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

这对上面的测试没有多大帮助,因为左边有 Bar 元素,右边有 Foo,所以 运算符== 在 Foo 将不会被考虑。定义对称全局 operator== 函数会很有用。

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

关于c++ - 运算符==比较两个不同的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34487314/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com