C++ how to call parent's friend function?
There is a Base class and a Derive class. Derive public inherit Base. The base class has implemented a friend function bool operator==(const Base& lhs,const Base& rhs) const; I am implementing the Derive class, which also need to implement bool operator==(const Derive& lhs, const Derive& rhs) const; Now my problem is that I do not know how to call the parents's operator== function in my operator== funct开发者_高级运维ion. The operator== for Base class dose not belong to base, so i cannot simply use Base::operator==. Thank you.
Bind references to the Base
subobjects, and compare them with normal operator syntax. An example:
class Base { /*...*/ };
bool operator==(const Base&, const Base&);
class Derive : public Base
{
friend bool operator==(const Derive&, const Derive&);
private:
int mem_;
};
bool operator==(const Derive& d1, const Derive& d2)
{
return static_cast<const Base&>(d1) == static_cast<const Base&>(d2)
&& d1.mem_ == d2.mem_;
}
Warning: A setup like this will silently slice if you accidentally compare a Base
to a Derive
. If the base class must be comparable, it might be worth setting up a virtual comparison mechanism.
精彩评论