Private inheritance VS composition : when to use which?(私有继承 VS 组合:何时使用哪个?)
问题描述
私有继承 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 组合:何时使用哪个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:私有继承 VS 组合:何时使用哪个?
基础教程推荐
- CString 到 char* 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
