简体   繁体   中英

c++ invoke base classes' virtual operator== with multiple inheritance

Given the following excerpts:

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

In C.cpp I'm trying to implement 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;
    }
}

I can get it to work for the output method, but I don't know how to do something equivalent when overriding operators:

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

Is there a way to call the base classes' virtual operators instead of doing something like adding a virtual equals() method and just having operator== call that?

(Note: this code is based off of a small part of a homework assignment in case that's relevant.)

You need to explicitly name the operator you want to use.

Replace:

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

With Edit: corrected

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

The two base classes should handle any type error in other , so you don't need to do anything about that here.

EDIT: rewrote code to use explicit call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM