How can I hide a class in C++?

后端 未结 4 592
旧时难觅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:30

    Instead of hiding class, I'd recommend diabling making use if it. In example:

    class Hidden
    {
      private:
        friend class Exposed;
        Hidden() {}
        int hidden_x;
    };
    
    class Exposed : private Hidden
    {
      public:
        Exposed() : Hidden() {}
        void DoStuff() { printf( "%d" , hidden_x ); }
    };
    

    So what you can: - create any number of Exposed class instances in your code - call DoStuff() method from these instances

    But you cannot: - instantiate Hidden class (private constructor) - operate on Hidden class members directly or via Exposed class (they are private)

提交回复
热议问题