继承Shell类供容器使用
让一组相关的类全部继承自同一个(本质上是空的)类,以便客户端可以将所有实例组织到一个容器中,这是否被认为是一种好的做法?
例如:
class One : public Foo { }
class Two : public Foo { }
class Three : public Foo { }
所以稍后我可以做 std::vector
s。
如果不是,什么被认为是好的做法?
Would it be considered good practice to have a group of related classes all inherit from the same (essentially empty) class, so the client can organize all of the instances into one container?
For example:
class One : public Foo { }
class Two : public Foo { }
class Three : public Foo { }
So later I can do std::vector<Foo*> myClasse
s.
If not, what is considered a good practice?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是实现多态类型的标准做法。然而,基类为空的情况并不常见。除此之外,它必须实现一个虚拟析构函数,并且通常必须提供其他(可能是纯)虚拟函数才能执行任何有用的操作。
It's the standard practice for implementing polymorphic types. However, it is unusual for the base class to be empty. Apart from anything else, it MUST implement a virtual destructor, and normally there are other (probably pure) virtual functions that must be provided in order to do anything useful.
只要为
Foo
添加一个虚拟析构函数,以便稍后可以dynamic_cast
,就应该没问题。As long as you add a virtual destructor to
Foo
so that you candynamic_cast
later, you should be okay.