简体   繁体   中英

How to modify a private array without giving too much freedom?

I have a class named A which contains a private , dynamically-allocated array of class B objects. I have an array of pointers(?) to elements of the B array inside of A (the first array described) and I need a function which would help me modify this array (to actually let me get and point to those elements).

What would it be the best way to work with? Pointers, references?
One way I thought of would be to create a getter within A which returns the address of the array or of an element of the array, but I think that it gives too much freedom outside the class.

Thank you (and sorry for confusing you with my question) but I am pretty new to these things. Hopefully, you will understand better with this drawing:

The ideal solution would be to be able, given an instance of A a and a handler to designate a unique instance of B owned by a , but without having total control over this B .

I'd suggest a simple index inside the array:

class A
{
    Array _array;
public:
    // ctr, operator=, ...
    const B& operator[](std::size_t index) const { return _array[index]; }
    B& operator[](std::size_t index) { return _array[index]; } // if necessary
};

Ou could also define an iterator for this array, or return a A::_array::const_iterator . The possibilities are infinite (kind of) and the best choice depends on your actual constrains.

If you really must use dynamic allocation, but wish to offer references to the Bs, you may do something like this:

struct B {};

struct A
{
    B& operator[](size_t i) {
        return *_bs[i];
    }

    const B& operator[](size_t i) const {
        return *_bs[i];
    }

    std::size_t size() const {
        return _bs.size();
    }

private:
    std::vector<std::unique_ptr<B>> _bs;
};

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