鉴于以下摘录:
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() 方法并让 operator== 调用它?
(注意:此代码基于家庭作业的一小部分,以防万一。)