【发布时间】:2014-12-12 21:39:22
【问题描述】:
我正在尝试编写一个具有一个基类(Employee)和两个派生类(Staff 和 Manager)的程序。 我将数据存储在链接列表中。
在尝试访问 Manager 的功能时,我遇到了由于我认为向下转换的问题? 当从节点的链表接收数据时,它假定它的类型为 Employee - 我需要它的类型为 Manager 以访问私有函数。 我试图向上转换它,但它不喜欢我使用变量的方式。
有谁知道如何解决这个问题并允许访问我的派生类中的函数? 请注意,我对此很陌生,所以如果我犯了明显的错误,请记住这一点!
void displayManagerDetails(const List<Employee*> list)
{
unsigned long longID = getID();
List<Employee*> temp(list);
system("CLS");
cout << "Name Department Salary\n";
cout << "--------------------------------------------------------\n\n";
while (!temp.isEmpty())
{
if (temp.first().data->getEmpNo() == longID && temp.first().data->getType() == "Manager")
{
Manager hold = temp.first();
Employee* pEmp = &hold;
Manager* test = dynamic_cast<Manager*>(pEmp);
cout << test->getSalary()
return;
}
temp.deleteFirst();
}
}
如果您需要更多代码,请告诉我,但我认为这就是所有相关的 :)
【问题讨论】:
-
那么你的问题是什么?
-
如果是私有函数,你期望如何在类外访问?
-
您不能在定义它们的类之外访问私有方法。将这些方法公开,然后尝试。
-
我不确定你的 List 或你的类是什么定义的(你应该提供相关信息)。但根据上下文线索,Manager hold = temp.first() 似乎不正确。为什么不 Manager * test = dynamic_cast( temp.first().data );