简体   繁体   中英

In class composition make possible for contained class to access container class variables

First consider the class declaration:

class Container
{
public:
    Container();
    void funcMember();
private:
    int dataMember;
};

class Contained
{
public:
    Contained();
    int contmember();
private:
    int somedata;
};

Now the idea is that the Contained class is made for being declared inside the Container class so it can be declared more than once and be created and deleted whenever you want, in this case from funcMember() in the Container class.

My question: Is there a way to make that every instance of Contained inside Container could access dataMember inside whatever Container instance?

Note: several Contained objects could hold different values in the somedata variable.

You can use friend and a nested class to do so:

Container.h :

class Container
{
    class Contained; // <<< Forward declare
    friend class Contained; // <<< Allow access from Contained
    class Contained
    {
    public:
        Contained(Container& cont_) : cont(cont_) {}
        int contmember();
    private:
         int somedata;
         Container& cont;
    };
public:
    Container();
    void funcMember();
private:
    int dataMember;
};

In another TU provide the implementation seeing the fully declared Container class:

Container.cpp

#include "Container.h"

int Container::Contained::contmember() {
    return cont.dataMember + somedata;
}

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