How can I hide a class in C++?

后端 未结 4 634
旧时难觅i
旧时难觅i 2021-01-11 23:49

Let\'s say I have 2 classes that I want to be visible (within a given header file) and one class that is their ancestor, which one I want to be visible only to the previousl

4条回答
  •  梦谈多话
    2021-01-12 00:26

    Abusing a class to act as a namespace will do this. I do not recommend this pattern.

    class hidden_stuff {
    private: // hide base from everyone
        struct base {
            // contents
        };
    public:
        class derived1;
    };
    typedef class hidden_stuff::derived1 derived1;
    
    class hidden_stuff::derived1
        : private hidden_stuff::base {}; // private inheritance required
                // or hidden_stuff::base is accessible as derived1::base
    

    The real solution (though not technically satisfying the question)

    A preferable solution would be to use a clearly-named namespace such as impl:: or detail::, which will convey to users that they shouldn't use any classes inside, and stop any possible undesired effects on overloading or the like. That's how most libraries (even Standard Library implementations) "hide" classes from the user.

提交回复
热议问题