虚拟函数如何在C ++中实现?

C ++中的虚函数用于创建基类指针列表和任何派生类的调用方法,甚至不知道派生类对象的种类。虚函数在运行时解析得较晚。

这是C ++程序中虚函数的实现-

示例

#include <iostream>
using namespace std;
class B {
   public:
      virtual void s() { //virtual function 
         cout<<" In Base \n";
      }
};
class D: public B {
   public:
      void s() {
         cout<<"In Derived \n";
      }
};
int main(void) {
   D d; // An object of class D
   B *b= &d; // A pointer variable of type B* pointing to d
   b->s(); // prints"D::s() called"
   return 0;
}

输出结果

In Derived