c ++调用基类'虚拟运算符==具有多重继承

时间:2013-04-15 18:14:21

标签: c++ operator-overloading multiple-inheritance

鉴于以下摘录:

class Interface {
public:
    virtual bool operator==(const Interface &other) const = 0;
    virtual void print(ostream& sout) const = 0;
};

class A : virtual public Interface {
public:
    virtual bool operator==(const Interface &other)const;
    virtual void print(ostream& sout)const;

protected:
    short m_foo;
};

class B : virtual public Interface {
public:
    virtual bool operator==(const Interface &other)const;
    virtual void print(ostream& sout) const;

protected:
    short m_bar;
};

class C: public A, public B {
public:
    virtual bool operator==(const Interface &other) const;
    virtual void print(ostream& sout) const;
};

在C.cpp中我试图实现operator ==:

bool C::operator==(const Interface &other) const {
    try {
        // This works, but it's duplicating code from A.cpp and B.cpp
        const C& otherC = dynamic_cast<const C&>(other);
        return (m_foo == otherC.m_foo && m_bar == otherC.m_bar);

        // This doesn't work -- it calls C::operator== instead of
        // A::operator== and B::operator== (infinite recursion).
        /*
        return (dynamic_cast<const A&>(*this) ==
                dynamic_cast<const A&>(other) &&
                dynamic_cast<const B&>(*this) ==
                dynamic_cast<const B&>(other));
                */
    } catch (bad_cast e) {
        return false;
    }
}

我可以让它为输出方法工作,但我不知道该怎么做 重写运算符时的等价物:

void C::print(ostream& sout) const {
    A::print(sout);
    sout << " ";
    B::print(sout);
}

有没有办法调用基类的虚拟运算符而不是执行 比如添加一个虚拟的equals()方法,只需要运算符== 是什么?

(注意:此代码基于家庭作业的一小部分,以防万一 这是相关的。)

2 个答案:

答案 0 :(得分:3)

您需要明确指定要使用的运算符。

替换:

    return (dynamic_cast<const A&>(*this) ==
            dynamic_cast<const A&>(other) &&
            dynamic_cast<const B&>(*this) ==
            dynamic_cast<const B&>(other));

使用修改:更正

    return (A::operator==( other ) &&
            B::operator==( other ));

答案 1 :(得分:0)

return A::operator==(other) && B::operator==(other);

这两个基类应该处理other中的任何类型错误,所以你不需要在这里做任何事情。

编辑:重写代码以使用显式调用。

相关问题