![](/img/trans.png)
[英]Question on multiple inheritance, virtual base classes, and object size in C++
[英]c++ invoke base classes' virtual operator== with 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()方法並只用operator ==那樣進行調用?
(注意:如果相關,此代碼基於作業的一小部分。)
您需要明確命名要使用的運算符。
更換:
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 ));
return A::operator==(other) && B::operator==(other);
這兩個基類應該處理other
任何類型錯誤,因此您無需在此做任何事情。
編輯:重新編寫代碼以使用顯式調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.