提问的动机
我正在学习 Model-View (paragraph Using a model) 的教程在 Qt 中使用模型。 该示例显示以下代码:
//Header file
class StringListModel : public QAbstractListModel
//main.cpp
QAbstractItemModel *model = new StringListModel(numbers);
附有以下解释。
Note that the StringListModel is declared as a QAbstractItemModel. This allows us to use the abstract interface to the model, and ensures that the code still works, even if we replace the string list model with a different model.
我是这样解读他们的回答的:
您可以在 model
上开发您的项目,如果您需要更改底层数据结构,您只需这样做:
//Header file
class NewStringListModel : public QAbstractListModel
//main.cpp
//QAbstractItemModel *model = new StringListModel(numbers); Stoped using this, old
QAbstractItemModel *model = new NewStringListModel(numbers); //complete model change with just a single line
广义
这是否被视为指针转换?
如果子类实现基类中不存在的方法,是否会造成问题?
它会是这样的:
pointerToParent->childMethodNotExistingInParent()
- 这是一种不好的做法吗?如果不是,为什么不呢?
最佳答案
是的,这是一个隐式向上转换(即在继承层次结构中向上,从子级到父级)。这与显式转换不同,在显式转换中,您可以准确指定期望的输出类型;它也不同于向下转型,向下转型是从父到子的继承层次结构。
是的,子类中的新方法/成员有点问题。它们不能通过父类指针直接访问。但是,您可以使用
dynamic_cast<>()
尝试将父指针转换为您期望的任何子类,并以这种方式访问新功能。但这不是理想的方法。你最好重构父/子类并使用virtual
功能来避免这种情况。一般来说,存储和使用父类指针并不是坏习惯。事实上,如果您的类层次结构实现“is-a”关系,通常被认为是一种好的做法,因为它保持了接口(interface)和实现之间的区别(理想情况下,一个不应该影响另一个的设计)。 但是,尝试通过(适当转换的)父指针访问仅限子级的功能是一个可疑的领域,因为它打破了接口(interface)实现的区别。不过在极少数情况下是必要的。
关于c++ - 在指向父对象的指针上初始化子对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19682402/