运行时多态意味着什么?

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)


lia*_*iaK 5

所提供的示例中不存在歧义.

如果基类具有与派生类相同的函数名,并且如果按照指定的方式调用,则它将调用基类的函数而不是派生类1.

在这种情况下,您可以使用virtual关键字,以确保从当前指向的对象调用该函数.它在运行时解决.

在这里您可以找到更多解释..