When should you use 'friend' in C++?

前端 未结 30 1999
孤街浪徒
孤街浪徒 2020-11-22 10:12

I have been reading through the C++ FAQ and was curious about the friend declaration. I personally have never used it, however I am interested in exploring the language.

30条回答
  •  遥遥无期
    2020-11-22 10:59

    Another common version of Andrew's example, the dreaded code-couplet

    parent.addChild(child);
    child.setParent(parent);
    

    Instead of worrying if both lines are always done together and in consistent order you could make the methods private and have a friend function to enforce consistency:

    class Parent;
    
    class Object {
    private:
        void setParent(Parent&);
    
        friend void addChild(Parent& parent, Object& child);
    };
    
    class Parent : public Object {
    private:
         void addChild(Object& child);
    
         friend void addChild(Parent& parent, Object& child);
    };
    
    void addChild(Parent& parent, Object& child) {
        if( &parent == &child ){ 
            wetPants(); 
        }
        parent.addChild(child);
        child.setParent(parent);
    }
    

    In other words you can keep the public interfaces smaller and enforce invariants that cut across classes and objects in friend functions.

提交回复
热议问题