【发布时间】:2013-07-09 15:34:08
【问题描述】:
我之前已经发布过这个问题 (Here),这是一种不同的解决方案。这个解决方案似乎更好地封装了那些实现类的行为,因为它可以防止他们需要显式地向上转换。
问题来了:
我有一个项目,我想在其中隔离大多数对象中的核心行为,同时通过派生对象提供其他行为。很简单:
class BaseA
{
virtual void something() {}
}
class DerivedA : public BaseA
{
void something() {}
void somethingElse() {}
}
现在假设我还有第二组类,相同的继承方案,只是它们聚合了上述类。但是,我希望基版本使用基类,派生版本在派生类中。我的解决方案是考虑使用相同的名称“隐藏”基类变量;
class BaseB
{
BaseA *var;
BaseB()
{
var = new BaseA();
}
virtual void anotherThing1();
virtual void anotherThing2();
virtual void anotherThing3();
}
class DerivedB : public BaseB
{
DerivedA *var;
DerivedB()
{
var = new DerivedA();
}
void anotherThing1();
void anotherThing2();
void anotherThing3();
void andAnother1();
void andAnother2();
}
这种方法的目标是让依赖于派生聚合类的函数不再需要显式转换来实现获得的功能。
void func1( BaseB &b )
{
b.anotherThing1();
b.var->something();
}
void func2( DerivedB &b )
{
b.anotherThing1();
b.andAnother1();
b.var->something();
b.var->somethingElse();
}
void main( int argc, char **argv )
{
BaseB baseB;
DerivedB derivedB;
func1( baseB );
func1( derivedB );
func2( derivedB );
}
这会被认为是不好的做法吗?
【问题讨论】:
-
你为什么要这样做?
Base* var不会为他们俩做吗?如果不是,你为什么要它们同名——这是故意阻止其他人能够阅读代码还是什么? -
我只是想获得有关这种方法的输入。我最初想只使用一个 Base *var(我的帖子开头的链接)。但是想知道这对于那些实现类的人来说是否更容易,因为他们永远不需要为派生功能显式转换
标签: c++ class inheritance casting polymorphism