使用基类和派生类创建链接列表

时间:2013-09-03 17:37:17

标签: c++

如何使用基类和派生类

创建链接列表

例如:

class Base { 
    int id;
    Base *next;
};
class Derived : public Base {
    string name;
};  

Base *list = NULL;

Base *b = new Base();
b->next = list;
list = b;

Derived *d = new Derived();
d->next = list;
list = d;

Base *itr = list;
while(itr) {
    if(typeid(Base) == typeid(*itr)) {
        cout << "Base: " << itr->id << endl;
    } else {
        cout << "Derived: " << itr->id << " and " << itr->name << endl;
    }
    itr = itr->next;
}

我的做法不起作用!有什么建议吗?

3 个答案:

答案 0 :(得分:1)

夫妻问题:

  • 字段是私有的
  • 你必须在你的其他地方强制转换为Derived才能使用name();

可能比检查typeid更好的解决方案是定义一个返回字符串表示形式并在Derived中覆盖它的虚函数。

答案 1 :(得分:0)

不要使用继承这种情况不要求它。你需要知道 Vertex和Super Vertex之间的区别。如果继承是正确的做法,你不需要知道差异。尝试以下方法。

class SuperNode;
class Base {
public:
    int id;
    Base *next;
    SuperNode* next;
};

class SuperNode {
public:
    string name;
    int id;
    Base *next;
    SuperNode* next;
};

答案 2 :(得分:0)

你想做什么工作正常。看到这个完整的例子:

#include <stdio.h>
#include <typeinfo>

struct Base {
    Base *next; int id;
    Base(int id) : id(id) {}
    virtual ~Base() {}
};

struct Derived : Base {
    int id2;
    Derived(int id, int id2) : Base(id), id2(id2) {}
};

void link(Base *n, Base **list) {
    n->next = *list; *list = n;
}

int main(int argc, const char *argv[]) {
    Base *list = 0;
    link(new Base(10), &list);
    link(new Derived(20, 21), &list);
    link(new Base(30), &list);
    link(new Derived(40, 41), &list);

    for (Base *p = list; p; p=p->next) {
        if (typeid(*p) == typeid(Base))
            printf("Base(%i)\n", p->id);
        else
            printf("Derived(%i, %i)\n", p->id, ((Derived *)p)->id2);
    }
    return 0;
}

但是,您必须至少有一个typeid虚拟成员才能工作。

相关问题