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 组合:何时使用哪个?
基础教程推荐
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01