【发布时间】:2015-05-10 15:42:47
【问题描述】:
好的,我有一个人员链接列表。但是,我可以将人员、员工、教员或学生添加到列表中,因为其他 3 个是子类。
教师指导:“添加子菜单项和相关功能(插入书),允许将新书添加到现有学生节点的书树中。新书必须插入正确的位置以维护二叉搜索树特性。必须输入学生姓名、书名、url等信息。为了简化程序,可以假设链表中的所有节点都是学生节点。
^^ ** 我想指出我看到她所说的简化假设所有链表都是学生节点,但是 Personnel/Employee/Faculty 和链表的所有代码都在作业中提供。所以,我能想到的“使用”的唯一方法是浏览所有代码,将任何从 Personnel 到 Student 的引用更改为任何引用,但这在那时似乎是一个相当愚蠢的任务......
所以我的问题是:我需要遍历链表,直到找到仅使用名称字段的正确条目。但随后我需要编辑与该条目相关联的 BookTree 类,该条目只有子类 Student 具有。由于类型与人员不匹配,我无法使用学生指针遍历链接列表(尽管列表中除了学生之外的任何内容都是空的),但是如果我使用人员指针找到它,我当然会赢'无权访问学生特定的功能来编辑我需要的内容。
我试过 Student *ptr = &PersonnelPtr 只是在找到正确的地址后为其分配地址,没有骰子。
代码:
int add_book()
{
char studentName[50]; // blah
PersonnelNode *temp, *prev;
Student *student;
temp = head;
prev = temp;
while (temp != NULL)
{
student = temp->getNode(); // this line gives "value of type Personnel* cannot be assigned to an entity of type Student*
if (_stricmp(studentName, student->getName()) != 0)
{
prev = temp; // loop through
temp = temp->getNext();
index++;
}
else
{
// Do Stuff
// More importantly in the do stuff part I need access to Student-specific data/functions that Personnel pointer won't see
【问题讨论】:
-
是
Personel派生自Student?如果是,它们是否通过虚函数实现了一个通用接口? -
Personnel 是父级。人事 > 员工 > 教职员工 > 学生
-
看来你必须投:(
Student* student = dynamic_cast<Student*>(tempNode); -
但是后来当我需要向学生添加书籍时,人员指针会出错。所以我不确定如何使用它。但是我认为我可以用任何一种方式解决虚函数的问题,几乎完成了尝试
-
是的,这似乎有效,谢谢@vsoftco 我不知道如何将其标记为已回答,可能是因为您刚刚在评论中回答了大声笑
标签: c++ inheritance linked-list