Saving part of an open nested class is visible only to the nesting class

I have a nested class in C ++ that should be publicly available. But I need some of his methods to be visible in the outside world, and the rest are visible only to the nesting class. I.e:

class set {
public:
    class iterator {
        innerMethod();
    public:
        outerMethod();
    }
}

I want to be able to write a method for set that uses innerMethod (). If I make it publicly available, I will also access it from outside, which I definitely don't want. Is there a way to do this without doing things “friend class”?

Thanks in advance!

+3
source share
5 answers

THERE IS NOT A GOOD WAY; you can do this without using a keyword friend.

In the comment you said:

, "", , " " , . , .

friend , , , . - ,, ? ? friend , -;, , - , , friend , . ++ - !

class set {
public:
 class iterator 
 {
  friend class set; //<---- this gives your class set to access to inner methods!

  void innerMethod(){}
 public:
  void outerMethod(){}
 };
 iterator it;

 void fun()
 {
  it.innerMethod();
  it.outerMethod();
 }
};

: , ,

+2

, , - , friend -directive.

friend , ?

+1

: 2 , ? , , ...

+1

, .

, - Key.

friend, .

class set;

// 1. Define the Key class
class set_key: noncopyable { friend class set; set_key() {} ~set_key() {} };

class set
{

  // 2. Define the iterator
  class iterator
  {
  public:
    void public_method();

    void restricted_method(set_key&);

  }; // class iterator

}; // class set

restricted_method , set iterator. , set_key... set .

, set set_key , . : -, . - ( , set ) Key.

, , *((set_key*)0). , ( ++).

+1
source

You can do something like this:

class set

{

public:
    class iterator
    {
        protected:
            iterator(){};
            virtual ~iterator(){};

        public:
            //outer world methods...
    };

private:
    class privateIterator : public iterator
    {
        public:
            privateIterator(){};
            ~privateIterator(){}

        //inner methods;
    };

public:
    iterator* CreateIterator()
    {
        return new privateIterator();//this is used to be sure that you only create private iterator instances
    }

};

I do not know if he answers correctly, but now he uses the work of a friend’s key, and he hides some of the methods. The only problem is that you cannot declare privateIterator, and you should always use CreateIterator to create an instance ...

0
source

Source: https://habr.com/ru/post/1785189/


All Articles