简体   繁体   中英

Sub-items having access to container values/variables (Box and contents example)

If I have a box, and inside I have a thousand items in it, I'm going to make a class called Box. Then I have a method in Box which is going to create a thousand items.

class Box
{
public:    
    bool isOpen = true;
    Item *p_boxContents  //Create pointer to a thousand Item objects

    void createBoxContents()
    {
        p_boxContents = new Item[1000];
    }

Now I have an Item class. Remember, I'm going to be creating many of these, and I want each of them to have access to the Box member variable isOpen . How can I do this without giving a pointer member to each instantiation of 'Item' pointing to the Box address?

At first I approached this by using class inheritance, but I was told that was wrong, and I understand that this situation falls more appropriately under the area of composition as opposed to inheritance.

I'm only beginning at programming and I've been trying to figure this out for days, anyone want to give me the obvious answer?

If no code should ever access the Item s from outside then you could use and inner class inside Box .

You can read about how the Item s would access the members in Box here :

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