简体   繁体   English

Qt和C ++:双重继承与合成?

[英]Qt and C++ : double inheritance vs composition?

My question is the following. 我的问题如下。 I want to make a new widget which is a QTableWidget + a QMenuBar (with a particular configuration of the QTableWidget ). 我想制作一个新的小部件,它是QTableWidget + QMenuBar (具有QTableWidget的特定配置)。 Currently, I have created a MyWidget which derives from QWidget and contains a QTableWidget + a QMenuBar . 当前,我已经创建了一个MyWidget,它是从QWidget派生的,并包含QTableWidget + QMenuBar But is it possible to do the same thing by deriving MyWidget from QTableWidget and QMenuBar ? 但是是否可以通过从QTableWidgetQMenuBar派生MyWidget来做同样的事情? And if it is possible what the constructor looks like? 如果可能的话,构造函数是什么样子?

Since both QTableWidget and QMenuBar inherit from QWidget, I strongly recommend not using double inheritance. 由于QTableWidget和QMenuBar都从QWidget继承,因此我强烈建议不要使用双重继承。 See, for example this question . 参见例如这个问题

What your doing currently is generally considered the "right" way, at least in Qt. 至少在Qt中,您当前所做的事情通常被认为是“正确”的方法。 I suspect the main reason you want to use multiple inheritance instead of composition is that you might feel like you have to write a bunch of functions just so that people who are using your widget can, for example, add to the QMenuBar. 我怀疑要使用多重继承而不是合成的主要原因是,您可能会觉得自己不得不编写一堆函数,以便使使用小部件的人可以将其添加到QMenuBar中。 Such a function might look like this: 这样的功能可能看起来像这样:

QAction *MyWidget::addMenuToMyQMenuBar(QMenu *menu)
{
    return myMenu->addMenu(menu);
}

To me this is a bit silly, and instead I would recommend simply making an accessor function for your QMenuBar: 对我来说,这有点愚蠢,我建议您简单地为您的QMenuBar制作一个访问器函数:

QMenuBar *MyWidget::menuBar()
{
    return myMenu;
}

Now someone using your class can just do 现在有人在使用您的课程就可以

myWidget->menu()->addAction(someAction);

This style of coding occurs quite commonly in the Qt source code and I consider it much cleaner. 这种编码风格在Qt源代码中很常见,我认为它更简洁。

This sounds like composition will suit your needs. 听起来构图会满足您的需求。

Inheritance satisfies the is-a relationship (NewWidget is a QTableWidget and NewWidget is a QMenuBar?) 继承满足is-a关系(NewWidget是QTableWidget,NewWidget是QMenuBar吗?)
Composition satisfies the has-a relationship (NewWidget has a QTableWidget and NewWidget has a QMenuBar?) 组合满足has-a关系(NewWidget具有QTableWidget,NewWidget具有QMenuBar?)

It is impossible to inherit from two QWidget's at once. 不可能一次继承两个QWidget。 Each QWidget is also a QObject. 每个QWidget也是一个QObject。 MOC (Meta-Object compiler) cannot handle such classes. MOC(元对象编译器)无法处理此类。

Inheritance - The relationship is X isa Y 继承-关系是X isa Y

Composition - The relationship is X has a Y 组成-关系是X具有Y

There is your answer - what is the relationship between X and Y? 您有答案-X和Y之间是什么关系?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM