简体   繁体   中英

Is a non-member friend function overloaded operator inherited?

I have my parent class B and I overloaded the << operator. It seems my derived class D can use that operator, even tho I read everywhere that classes don't inherit friend functions from their parents. I used public inheritence by the way.

I am confused. Does this work because it is an overloaded operator, or any friend function is inherited by the child. Also if they are inherited, can I redefine them in any way?

If you have overloaded the friend operator<< for B, you may invoke that operator for D, even if it is not a freind of D:

class B {
public: 
    B(int i=0):v(i){}
private:
    int v;
friend ostream& operator<< (ostream& os, const B& b);
};

class D:public B {
public:
    D(string s=""s,int i=1) : B(i),v2(s){}
private:
    string v2;
};

// access to the private members of B.  B is accessed via a reference. 
ostream& operator<< (ostream& os, const B& b){
    return os<<b.v; 
}

int main() {
    B b;
    D d; 
    cout << b <<endl;  // calls operator<< for B
    cout << d <<endl;  // calls operator<< for the B sub-object of D
}  

Online demo

For the D object, the B subject of D is used, since my code above passes argument by reference. If the overload would pass arguments by value instead of by reference, it would work as well, but the d object would be sliced into a B object.

In both case, the operator overload for the parent class is invoked.

You can overload the operator for the child class as well. But since friendship is not inherited, you'd need to define a new freindship if you need to access private members:

ostream& operator<< (ostream& os, const D& d){
    //return os<<d.v<<d.v2; // not alloewed because D has no visibility on B's private members
    return os << *static_cast<const B*>(&d) << d.v2; 
}

Demo

The friendship for D is limited to D's private members and does not give access to B's private member. The usual way is to invoke the overload for B (here via a casting trick), and access the private member of D.

Of course, if operator<< only accesses public members we don't need any freindshop for the overload.

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