[英]Calling a 3rd layer subclass using a 1st layer pointer
I made a class hierarchy where the 1st layer super class is staff. 我建立了一个类层次结构,其中第一层超级类是职员。 In my 2nd layer I have 2 subclasses called admin staff and academic staff.
在第二层中,我有2个子类,分别称为管理员和学术人员。 (These two layers are also abstract classes).
(这两层也是抽象类)。 Academic staff have 2 more subclasses teaching only and research only.
学术人员还有2个仅用于教学和研究的子类。
In my main, am trying to create an array of 10 staff pointers(5 of admin and 5 of academic) and manipulate 3rd layer subclasses using the pointers. 在我的主要工作中,我试图创建一个由10个职员指针组成的数组(5个管理员和5个学术指针),并使用这些指针操纵第三层子类。 Bare in mind the 3rd layer subclasses have behaviors which are not present in the in 1st or 2nd layer.
切记第三层子类的行为在第一层或第二层中不存在。 Hence, I have to use type casting.
因此,我必须使用类型转换。 I can change my 3rd layer behavior individually like eg,
我可以分别更改第三层的行为,例如,
((ResearchStaff *)ptr[i])->setResearchHour(23);
but it gets very messy very quickly. 但很快就会变得非常混乱。 My question, how can i access my 3rd layer behaviors in a for or while loop without having to individually set them.
我的问题是,如何在for或while循环中访问我的第3层行为,而不必单独设置它们。 Heres the main that im working with.
这是与我合作的主要工具。 Thanks A LOT!!
非常感谢!!
int main()
{
Staff *ptr[10];
for(int i=0;i<10;i++)
{
ptr[i] = new AdminStaff;
((AdminStaff *)ptr[i])->setAdmin(12);
i++;
ptr[i] = new TeachingStaff;
(( TeachingStaff*)ptr[i])->setTeaching(16);
}
}
Two things! 两件事情!
AdminStaff
or TeachingStaff
, you don't have to typecast back to base to invoke a derived class method. AdminStaff
或TeachingStaff
,不必强制转换回base即可调用派生类方法。 So instead of, 所以代替
ptr[i] = new TeachingStaff;
(( TeachingStaff*)ptr[i])->setTeaching(16);
you can write something like, 你可以这样写
TeachingStaff *ts = ptr[i] = new TeachingStaff;
ts->setTeaching(16);
Finally, if these classes do not have many attributes in common you can consider composition as an alternate design strategy instead of using multiple inheritance. 最后,如果这些类没有很多共同的属性,则可以考虑将组成作为替代设计策略,而不是使用多重继承。
You could use the Visitor pattern. 您可以使用Visitor模式。
Add a method to your Staff
class called accept
, like this: 在您的
Staff
类中添加一个名为accept
,如下所示:
class Staff
{
//Other staff stuff
public:
void accept(const Visitor& v) = 0;
}
Add implementations to your leaf classes... 将实现添加到叶类中...
class ResearchTeacher
{
//Other research teacher stuff...
public:
void accept(const Visitor& v) {
v.visit(*this);
}
}
Then define a Visitor that knows what to do with each type: 然后定义一个访问者,该访问者知道如何处理每种类型:
class Visitor
{
public:
void visit(ResearchTeacher& teacher)
{
teacher.setResearch(16);
}
void visit(TeachingTeacher& teacher)
{
teacher.setTeaching(16);
}
void visit(AdminStaff& admin)
{
admin.setAdmin(12);
}
}
Now the calling code doesn't have to worry about it: 现在,调用代码不必担心:
int main()
{
Visitor v;
Staff *ptr[10];
for(int i=0;i<10;i++)
{
ptr[i] = new AdminStaff;
ptr[i]->accept(v);
i++;
ptr[i] = new TeachingStaff;
ptr[i]->accept(v);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.