Best way to insert elements from the constructor of the Derived class into a private class of the std :: vector class?

I have the following classes:

class Base
{
...
private:
std::vector<X> v;
};

class Derived : public Base
{
Derived(X*, int n);
};

where the array of the Xs element is passed to the Derived constructor, which I need to insert into my vector v in the base class. (X is a smart pointer)

I currently see two ways to do this:

  • Create a function in the database: InsertItem (X *), which inserts an element into a vector (1 on 1)
  • Create a vector in Derived that contains the complete list, then enter it into the database to move the entire vector.

I don't see any advantages for # 2, but wondered if # 1 was a good solution, or if there are better ways to do this.

Thank!

+3
source share
5 answers

, Base. protected, :

class Base
{
...
protected:
    std::vector<X> v;
};

v. Derived, .

, ( № 1) :

class Base
{
...

protected:
    void push_back(const X &x)
    {
        v.push_back(x);
    }

private:
    std::vector<X> v;
};
+5

- ( ), . .

class Base
{
 . . .
protected:
    Base(X* x,int n);
 . . .
};

class Derived : public Base
{
    Derived(X* xes, int n):Base(xes,n){};
};
+4

, protected Base, X* , Derived, Derived, Base .

+1

, , ( ) Base, . , Base (Derived vector), Derived :

class Base
{
...
private:
    std::vector<X> v;

protected
    template <class iterator_t>
    void assign( iterator_t first, iterator_t last) {
        v.assign( first, last);
    }
};

class Derived : public Base
{
Derived(X* p, int n) {
    Base::assign( p, p+n);
}
};

, , , , . zdan, Base, ( ).

STL.

+1

You must set the member variable protectedso that classes that inherit Basecan access it. Alternatively, keep the member variable private, but add an accessor method protectedto allow classes that inherit Baseto add to the vector, etc.

0
source

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


All Articles