如何检查一个C++类是否扩展另一个(如果另一个是接口)?

Rel*_*lla 2 c++ oop extension-methods interface

所以一般都有

class A { ... };
class B { ... };
class C: public A, public B {};  // C inherits from A and B.
Run Code Online (Sandbox Code Playgroud)

当我们创建一个C实例并希望将它传递给某个函数时,我们是否检查传递给函数的类是否正在扩展A?

ere*_*eOn 9

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

一个实例C也必须是A(和a B).

但是,如果你有一个函数A作为参数,你可以dynamic_cast<>用来检查实例是否实际上是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.
  }
}
Run Code Online (Sandbox Code Playgroud)

但是,要使其工作,基类类型必须是多态的(它必须至少具有虚方法).