简体   繁体   中英

C++ friend class map

So i have problem trying to access a friend class properties, i need a pointer to the first item in the map.

class.h

class A{

    private:
    map<int,float> database;
    public:
    ......
    class B{
        private:
          map<int,float>::iterator it;
        public:
            friend class A;
            B begin();
    }

}

and implem.hxx

A::B A::B::begin(){
            A::B it;
            ite.it = database.begin();
            return ite;
}

But it shows a problem when compiling: error: invalid use of non-static data member A::database

How can i resolve the problem?

Besides some syntax issues, I see the A::database variable is attempted to be accessed in A::B::begin() . But this variable is not static to access it in that way, and class B is not derived from A as well. So, that the question imho has nothing to do with the friendship.

First thing to note is that it is completely redundant to make A a friend of B. Inner classes in C++ have access to private members of outer classes. However, when you're creating an instance of B, in there is no instance of class A, for which you are trying to access the map. You need an instance.

A::B doesn't have an enclosing creating instance of A like in Java for example - begin needs an object of type A to access its database :

A::B A::B::begin(A& a) {
    A::B b;
    b.it = a.database.begin();
    return b;
}

Note that A::B doesn't need to declare A as friend to access private members of A ( friend works the other way around) B already has access to the private members since it is nested.

It seems to me you wanted to wrap iterators of A::database in B , so hopefully this points you in the right direction:

class A {
    std::map<int,float> database;

public:
    class B {
        friend class A;
        std::map<int,float>::iterator it;
        explicit B(std::map<int,float>::iterator it) : it(it) { }
        ...
    };

    B begin();
};

A::B A::begin() {
    return B(database.begin());
}

Now begin is a member function of A and creates a B using a private constructor only A may access. Here's the usage code:

A a;
A::B b = a.begin();
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM