如何检查一个 C++类扩展另一个类(就像另一个类是接口一样)?
因此,通常
class A { ... };
class B { ... };
class C: public A, public B {}; // C inherits from A and B.
当我们创建 C 的实例并希望将其传递给某个函数时,我们会检查传递给函数的类是否扩展了 A 吗?
So generally having
class A { ... };
class B { ... };
class C: public A, public B {}; // C inherits from A and B.
when we create an instance of C and want to pass it into some function ho do we check if class we pass to a function is extending A?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
C
被定义为从A
继承,因此无需检查:C
的实例必须也是A
(和B
)。但是,如果您有一个将
A
作为参数的函数,则可以使用dynamic_cast<>
来检查实例是否实际上是C
:但是,要使其工作,基类类型必须是多态的(它必须至少有一个虚拟方法)。
C
is defined as inheriting fromA
so there is no need to check:It is mandatory that an instance of
C
is also aA
(and aB
).However, if you have a function taking a
A
as a parameter, you can usedynamic_cast<>
to check if the instance is actually aC
:For this to work, however, the base class type must be polymorphic (it must have at least a virtual method).
您唯一需要执行此操作的时间是在编译期间,因为隐式转换在其他任何地方都适用。但是如果你想查看某个类型 T 是否是某个类型 S 的基类,那么你可以使用 SFINAE (或者只使用 is_base_of<>):
The only time you'd need to do this is during compile time since implicit conversion works everywhere else. But if you want to see if some type T is a base of some type S then you can use SFINAE (or just use is_base_of<>):