linked lists with inherited classes in c++?

2019-07-21 09:25发布

问题:

I'm creating a list of classes for a program. However, the base class has multiple children, and some of the children have children as well. Would I need to alter my list in any way to accommodate the inherited classes? Thanks for any help!

Great, thanks for the help! This is an incredibly basic question, but when creating a grandchild class, would this be proper formatting?

Class C: Public B: Public A {

or just

Class C: Public B { ?

回答1:

Take the following program:

#include <iostream>
#include <list>

struct A
{
    virtual void hello()
       { std::cout << "Hello from A\n"; }
};

struct B : public A
{
    virtual void hello()
       { std::cout << "Hello from B\n"; }
};

int main()
{
    std::list<A>  l1;
    std::list<A*> l2;
    A a;
    B b;

    l1.push_back(a);
    l1.push_back(b);

    l2.push_back(&a);
    l2.push_back(&b);

    l1.front().hello();
    l1.back().hello();

    l2.front()->hello();
    l2.back()->hello();
}

We declare two lists, one using instances of class A, and one using pointers to A. You can put instances of B in the first list, since B is an A (due to inheritance). However, when you try to access the data and methods from items in the first list, you can not access data from B the items thinks they are of class A even if they are not.

For the second list it works though, because of the use of pointers and virtual overloading of the method.

I hope this helps a little with your question.



回答2:

You are probably not creating a list of classes, but rather of instances of classes. There is a big difference. While a "class" is just the definition of data members and functions, an instance actually fills this definition with life.

That aside, you cannot put an instance of an inherited class into a list that has the parent class as storage type. This only works if you store pointers or references to the instances in the list and allocate the instances themselves elsewhere.



回答3:

Problem with STL containers and inheritance is that STL containers store copies of objects, so all extended properties of child classes are lost in progress. Solution is to leave objects alone and do not copy them.

In STL containers you can store [smart] pointers to base class, so only pointer will be copied. Or you can go with intrusive lists like Boost::Intrusive or queue.h



回答4:

it is only :

class C: public B {

and of course :

class B : public A {

C is a subclass of B which is a subclass of A.

if you want a list of a mix of instances of A, B and C, you have to declare it :

list<A*> myClassList;