如何使用基类和派生类创建链表
例如。:
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;
}
我的方法不起作用!有什么建议么?