How is it right to pursue aggregated classes?


  • QA Engineer

    These are basic classes:

    class Foo {};
    class Bar
    {
        QList<Foo> fooList;
        //функции для работы с fooList;
    };
    

    How to make it possible to write classes of heirs

    class FooEx : public Foo {};
    class BarEx : public Bar {};
    class FooExList : QList<FooEx> {};
    

    In BarEx, replace the type of field fooList with

    QList<Foo> fooList
    

    FooExList fooList?
    

    I can't find a beautiful solution.



  • It is possible to reclassify in the original class the base class variable member and use virtual functions. The code below illustrates the idea and proves its functionality:

    #include <cstdio>
    

    class A {
    public :
    virtual void whoAmI() const {
    printf("class A.\n");
    }
    };

    class A1 : public A {
    public :
    virtual void whoAmI() const {
    printf("class A1.\n");
    }
    };

    class B {
    private :
    A a;
    public :
    virtual void whoAmI() const {
    printf("I am class B with member of ");
    a.whoAmI();
    }
    };

    class B1 : public B {
    private :
    A1 a;
    public :
    virtual void whoAmI() const {
    printf("I am class B1 with member of ");
    a.whoAmI();
    }
    };

    int main() {
    B b;
    B1 b1;
    B* pb = new B;
    B* pb1 = new B1;

    b.whoAmI();
    b1.whoAmI();
    pb-&gt;whoAmI();
    pb1-&gt;whoAmI();
    
    return 0;
    

    }

    Programme withdrawal:

    I am class B  with member of class A.
    I am class B1 with member of class A1.
    I am class B with member of class A.
    I am class B1 with member of class A1.

    Supplement

    We can do the following. Keep it in class. Bar not the object itself, but the index at the base class object and in the derivative classes BarEx To create the required class object:

    class Bar {
    protected :
    QList<Foo> pFooList = nullptr;
    Bar(QList<Foo>
    _pFooList) : pFooList(_pFooList) { }
    public :
    Bar() : pFooList(new QList<Foo>()) { }
    }

    class BarEx {
    public :
    BarEx() : Bar(new FooExList()) { }
    }

    Inadequacy of this method in the derivative classes pFooList will have the type of reference marker. But it's easy to deal with the type.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2