我想知道如何在下面给出的场景中避免代码重复。
(有这个问题:
How do I check if an object's type is a particular subclass in C++?
答案是,它是不可能的,即使是动态演员也无法访问成员,我猜。)
所以我想知道如何避免在不同的方法中使用几乎相同的代码,只有一种方法可以进行一些额外的操作。
class Basic {
...
}
class Advanced : public Basic {
...
}
AnotherClass::lengthy_method(Basic *basic) {
// do a lot of processing, access members of basic
if (*basic is actually of class Advanced)
// do one or a few specific things with members of Advanced
// more processing just using Basic
if (*basic is actually of class Advanced)
// do one or a few specific things with members of Advanced
// more processing just using Basic
}
同样从设计角度AnotherClass::lengthy_method
不希望在Basic
或Advanced
中定义,因为它并不真正属于他们中的任何一个。它只是在同类中运作。
我很好奇语言专家知道什么,我希望有一个很好的解决方案,至少可以通过C ++ 11的一些功能。
答案 0 :(得分:2)
dynamic_cast
成员被声明为Advanced
,或public
被声明为AnotherClass
,就可以在此处使用 friend
} Advanced
:
AnotherClass::lengthy_method(Basic *basic) {
// do a lot of processing, access members of basic
Advanced *adv = dynamic_cast<Advanced*>(basic);
if (adv != NULL) {
// use adv as needed...
}
// more processing just using Basic
if (adv != NULL) {
// use adv as needed...
}
// more processing just using Basic
}
另一种选择是使用多态而不是RTTI。在Basic
中展示一些不执行任何操作的其他虚拟方法,然后Advanced
覆盖它们:
class Basic {
...
virtual void doSomething1() {}
virtual void doSomething2() {}
}
class Advanced : public Basic {
...
virtual void doSomething1();
virtual void doSomething2();
}
void Advanced::doSomething1() {
...
}
void Advanced::doSomething2() {
...
}
AnotherClass::lengthy_method(Basic *basic) {
// do a lot of processing, access members of basic
// do one or a few specific things with members of Advanced
basic->doSomething1();
// more processing just using Basic
// do one or a few specific things with members of Advanced
basic->doSomething2();
// more processing just using Basic
}