2012-04-09 77 views
1

如果我要继承一个类,我是否必须定义它的所有虚拟和纯虚函数?C++ - 继承虚函数实现

例如,我有一个继承自QAbstractItemModel的派生类。 QAbstractItemModel具有以下纯虚函数。如果我的派生类不打算使用index()parent()方法,是否需要实现它?

//qabstractitemmodel.h 
virtual QModelIndex index(int row, int column, 
           const QModelIndex &parent = QModelIndex()) const = 0; 
virtual QModelIndex parent(const QModelIndex &child) const = 0; 
virtual int rowCount(const QModelIndex &parent = QModelIndex()) const = 0; 
virtual int columnCount(const QModelIndex &parent = QModelIndex()) const = 0; 
virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const = 0; 
+0

http://stackoverflow.com/questions/2089083/pure-virtual-function-with-implementation - 是的,你将不得不在你的派生类中定义纯虚函数,如果该类将被实例化。 'QAbstractItemModel'不提供'index'或'parent'的定义,所以你需要提供你自己的。如果它提供了实现,你可以从你的子类调用基类的版本。 – birryree 2012-04-09 20:49:04

+0

http://stackoverflow.com/questions/2089083/pure-virtual-function-with-implementation – 2012-04-09 20:52:49

+0

[C++ Virtual/Pure Virtual Explained]的可能重复(http://stackoverflow.com/questions/1306778/c-virtual - 纯虚拟解释) – 2012-04-09 20:53:31

回答

2

是。将方法声明为纯虚拟('= 0')意味着任何具体的子类(可以实例化)都必须实现它们。

3

您不必在派生类中都实现什么,但派生类仍然是抽象的,如果你留下任何的纯虚成员函数没有实现(换句话说,你赢了无法实例化该类的对象)。

编辑: 别的东西要考虑 - 如果你的基类,包含你的派生类不想纯虚函数/需要,也许值得考虑的替代设计?也许使用声明接口不同部分的多个基类。

如果index()parent()并不适用于所有的QAbstractItemModel派生类的话,我要说的这些功能有可能不属于QAbstractItemModel真正

+1

我已经看到它派生类被故意遗漏在基类中的位置,因为规范已更改并创建了新类。虽然您可以在过期的派生类上调用基类函数,但它不起作用。这完全取决于您的整体设计。这并不坏,只是不理想。 – 2012-04-09 20:57:13