Why does C++ not allow inherited friendship?

前端 未结 10 1586
终归单人心
终归单人心 2020-11-28 04:11

Why is friendship not at least optionally inheritable in C++? I understand transitivity and reflexivity being forbidden for obvious reasons (I say this only to head off sim

10条回答
  •  星月不相逢
    2020-11-28 04:32

    A friended class may expose its friend through accessor functions, and then grant access through those.

    class stingy {
        int pennies;
        friend class hot_girl;
    };
    
    class hot_girl {
    public:
        stingy *bf;
    
        int &get_cash( stingy &x = *bf ) { return x.pennies; }
    };
    
    class moocher {
    public: // moocher can access stingy's pennies despite not being a friend
        int &get_cash( hot_girl &x ) { return x.get_cash(); }
    };
    

    This allows finer control than optional transitivity. For example, get_cash may be protected or may enforce a protocol of runtime-limited access.

提交回复
热议问题