Nar*_*uto 2 c++ polymorphism inheritance runtime
我对运行时多态性感到有些困惑.如果我错了,请纠正我,但据我所知,运行时多态意味着函数定义将在运行时得到解析.
举个例子:
class a
{
a();
~a();
void baseclass();
}
class b: class a
{
b();
~b();
void derivedclass1();
}
class c: class a
{
c();
~c();
void derivedclass2();
}
Run Code Online (Sandbox Code Playgroud)
呼叫方法:
b derived1;
a *baseptr = &derived1; //here base pointer knows that i'm pointing to derived class b.
baseptr->derivedclass1();
Run Code Online (Sandbox Code Playgroud)
在上面的调用方法中,基类知道它指向派生类b.
那么歧义在哪里存在?
在什么情况下,函数定义会在运行时得到解决?
小智 10
此代码在运行时调用f()的正确版本,具体取决于实际创建的对象(A或B)的类型 - 没有"歧义".在编译时无法识别该类型,因为它是在运行时随机选择的.
struct A {
virtual ~A() {}
virtual void f() {}
};
struct B : public A {
virtual void f() {}
};
int main() {
A * a = 0;
if ( rand() % 2 ) {
a = new A;
}
else {
a = new B;
}
a->f(); // calls correct f()
delete a;
}
Run Code Online (Sandbox Code Playgroud)