如何检查一个C ++类是否扩展了另一个(就像另一个是接口)? [英] How to check if one C++ class extends another (like if that another one was an interface)?

查看:154
本文介绍了如何检查一个C ++类是否扩展了另一个(就像另一个是接口)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以一般有

class A { ... };
class B { ... };
class C: public A, public B {};  // C inherits from A and B.

当我们创建一个C实例并想传递它到某些函数,我们检查类是否传递给一个函数是否扩展A?

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?

推荐答案

C 定义为继承自 A ,因此无需检查:

C is defined as inheriting from A so there is no need to check:

C 的实例也是 A (和 B )。

但是,如果你有一个以 A 为参数的函数,使用 dynamic_cast<> 来检查实例是否实际上是 C

However, if you have a function taking a A as a parameter, you can use dynamic_cast<> to check if the instance is actually a C:

void function(const A& a)
{
  const C* c = dynamic_cast<const C*>(&a);

  if (c)
  {
    // a is an instance of C and you can use c to call methods of C
  } else
  {
    // a is not an instance of C.
  }
}

但是,要使这个工作,基类类型必须是多态(它必须至少有一个虚方法)。

For this to work, however, the base class type must be polymorphic (it must have at least a virtual method).

这篇关于如何检查一个C ++类是否扩展了另一个(就像另一个是接口)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆