私有继承 VS 组合.
Private inheritance VS composition.
我有点困惑何时使用它们.由于私有继承在某种程度上密封了继承链,给定:
I'm having a little confusion when to use each. Since private inheritance seals, in a way, the chain on inheritance, given:
class A
{
private:
int z;
protected:
int y;
public:
int x;
};
class B : private A
{
/* B's data members and methods */
/* B has access only to A's public and protected */
};
class C : public B
{
/* can access no fields of B */
};
C
将无法使用任何 B
的字段.什么时候用私有继承,什么时候用组合?
C
won't be able to use any of B
's fields. When would I use private inheritance, and when would I use composition?
谢谢!
此 C++ FAQ 条目 恰当地回答了您的问题.
This C++ FAQ entry answers your questions aptly.
复制到这里:
尽可能使用组合,必要时使用私有继承.
Use composition when you can, private inheritance when you have to.
通常您不想访问太多其他类的内部结构,私有继承为您提供了一些额外的权力(和责任).但私有继承并不邪恶;只是维护成本更高,因为它增加了有人更改会破坏您代码的内容的可能性.
Normally you don't want to have access to the internals of too many other classes, and private inheritance gives you some of this extra power (and responsibility). But private inheritance isn't evil; it's just more expensive to maintain, since it increases the probability that someone will change something that will break your code.
私有继承的合法、长期用途是当您想要构建一个 class Fred
使用 class Wilma
中的代码以及 中的代码>class Wilma
需要从您的新类 Fred
调用成员函数.在这种情况下,Fred
调用 Wilma
中的非虚拟,而 Wilma
调用本身(通常是纯虚拟),它们被 弗雷德
.这将很难用组合来实现.
A legitimate, long-term use for private inheritance is when you want to build a class Fred
that uses code in a class Wilma
, and the code from class Wilma
needs to invoke member functions from your new class, Fred
. In this case, Fred
calls non-virtuals in Wilma
, and Wilma
calls (usually pure virtuals) in itself, which are overridden by Fred
. This would be much harder to do with composition.
class Wilma {
protected:
void fredCallsWilma()
{
std::cout << "Wilma::fredCallsWilma()
";
wilmaCallsFred();
}
virtual void wilmaCallsFred() = 0; // A pure virtual function
};
class Fred : private Wilma {
public:
void barney()
{
std::cout << "Fred::barney()
";
Wilma::fredCallsWilma();
}
protected:
virtual void wilmaCallsFred()
{
std::cout << "Fred::wilmaCallsFred()
";
}
};
这篇关于私有继承 VS 组合:何时使用哪个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!