Can derived class use friend function of the basis class?
If I have some class Basis, and derived from it Derived, inside basis I have friend function
friend int operator!=(const Basis&, const Basis&)
Inside derived class I don't have such function So my question is if I have inside my main
If( derived1 != derived2 ) ...
why does it work? i don't have any constructor for casting for != th开发者_JS百科anks in advance If I write if ( derived != basis ) will it work?
The compiler is comparing them as objects of class Basis
. Since you can always implicitly convert from a derived class to a base class, the compiler is able to pass them to the Basis
overload of operator !=
. Of course, this comparison can only use fields declared in Basis
, so if you want the comparison to be more specific by using members of Derived
, you'll have to define a separate operator !=
overload.
The friendship declaration isn't relevant when it comes to calling operator !=
; all it does is allow operator !=
to access private members declared in Basis
.
It sounds like your friend function only compares the Basis
parts of Derived
. So, it works after a fashion, but ignores any data in Derived
.
Because your Derived class inherits everything that your Basis class has, which in this case is an operator overload for !=, your Derived objects (derived1 and derived2) also have them defined.
精彩评论