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?
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)
但是,要使其工作,基类类型必须是多态的(它必须至少具有虚方法).