链接列表与继承类在c ++? [英] linked lists with inherited classes in c++?

查看:128
本文介绍了链接列表与继承类在c ++?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为一个程序创建一个类的列表。然而,基类有多个孩子,并且一些孩子也有孩子。我需要改变我的列表以任何方式来适应继承的类吗?感谢任何帮助!

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?

C类:公共B:公共A {

Class C: Public B: Public A {

或只是

C类:

推荐答案

采取以下程序:

#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();
}



我们声明两个列表,一个使用类 A ,一个使用指向 A 的指针。您可以将 B 的实例放在第一个列表中,因为 B code>(由于继承)。但是,当您尝试从第一个列表中的项目访问数据和方法时,您无法访问来自 B 的项目认为它们属于

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.

这篇关于链接列表与继承类在c ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆