linked lists with inherited classes in c++?

2019-07-21 09:49发布

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 { ?

4条回答
够拽才男人
2楼-- · 2019-07-21 10:02

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楼-- · 2019-07-21 10:05

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;
查看更多
放荡不羁爱自由
4楼-- · 2019-07-21 10:10

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.

查看更多
时光不老,我们不散
5楼-- · 2019-07-21 10:13

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

查看更多
登录 后发表回答