在 C++ 中使用类层次结构时是否应该避免向下转型?
假设我正在编写一个适用于项目的应用程序,并根据项目的类型公开不同的功能。我有不同类型项目的类层次结构:
class AbstractProject
{
};
class ProjectA : public AbstractProject
{
};
class ProjectB : public AbstractProject
{
};
class ProjectC : public AbstractProject
{
};
现在,我计划将 AbstractProject *_currentProject 指针作为应用程序主类中的成员,在启动时弹出一个对话框,并根据选择执行以下操作:
_currentProject = new ProjectB(); // e.g.
稍后,我必须将指针向下转换为特定类型,以利用特定于不同项目的功能。不知何故,这让我感到不安。有更好的方法吗?
Let's say I'm writing an application which works with projects, and exposes different functionality depending on the type of the project. I have a hierarchy of classes for the different types of projects:
class AbstractProject
{
};
class ProjectA : public AbstractProject
{
};
class ProjectB : public AbstractProject
{
};
class ProjectC : public AbstractProject
{
};
Now, I was planning to have an AbstractProject *_currentProject pointer as a member in the application's main class, pop up a dialog box on startup and based on the selection, do:
_currentProject = new ProjectB(); // e.g.
Later, I'll have to downcast the pointer to the specific type to utilize the functionality specific to different Project-s. Somehow this makes me feel uneasy. Is there a Better Way of doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
更好的方法是在基类中定义纯虚方法,然后在派生类中的重载中实现所有特定功能。然后调用该方法。
Better way is to define pure virtual methods in base class and later implement all specific functionality in overloads in derived classes. Then call that method.
是的,只要可能,您应该使用虚拟方法。
Yes you should use virtual methods instead, whenever possible.
命令模式和访客模式都可以应用在这里。您应该自行决定哪种更适合您的情况。
http://en.wikipedia.org/wiki/Command_pattern
http://en.wikipedia.org/wiki/Visitor_pattern
The Command and the Visitor pattern may both apply here. You should decide for yourself which fits better for your case.
http://en.wikipedia.org/wiki/Command_pattern
http://en.wikipedia.org/wiki/Visitor_pattern
在纯面向对象中,您应该像每个人都建议的那样拥有虚拟方法。但是,如果您仍然需要特定的成员函数,请尝试使用其中一种设计模式,可能是命令或访问者甚至装饰器......
In pure OO, you should have virtual methods like everyone suggested. However, if you still need to go for specific member functions, try using one of the design pattern, may be command or visitor or even decorator...