I am trying to implement a QToolBar subclass, which has its items specified by a model, instead of added individually. This means a selection of functions to add/remove items (toolbar buttons), such as a开发者_StackOverflow社区ddAction shouldn't be publicly accessible.
What is the best way to inherit from this object, but make a selection of functions private?
My current best idea is to do like this:
class ToolbarView : public QToolBar
{
Q_OBJECT
public:
explicit ToolbarView(QWidget *parent = 0);
signals:
public slots:
private:
void addAction (QAction *action) {Q_UNUSED(action)};
QAction* addAction (const QString &text) {return QToolBar::addAction(text) ;}
...
QAction* addSeparator() {QToolBar::addSeparator();}
... [list of about 10 of these]
};
So, redefining all the functions that should not be public, as private.
Is this a good idea, or are there better methods?
As long as you inherit publicly from QToolBar
, you make it possible for a client code to treat your object as such and call for example the addAction
member function. If you want to ensure that these functions are inaccessible, you'll have do this the other way :
- Inherit privately from
QToolBar
- Publicly expose the functions you wish to expose (for example with
using
declarations)
If you want to stick with your initial solutions and inherit publicly from QToolbar
:
- Be aware that it doesn't guarantee base class functions won't be called
- You should consider using
using
declarations to change the accessibility of the base class functions instead of hiding them
Maybe you could think of this
class ToolbarView : private QToolBar
{
//...
}
In such case, all of accessible QToolBar will be with private access in your ToolbarView .
You are publically inheriting from QToolbar
. How about changing that to private
inheritance. That, is the class definition should begin as
class ToolbarView : private QToolBar
{
// good only if you want to
// make "most" of the public members of QToolBar private in ToolbarView
}
精彩评论