C ++中的内联虚函数

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

虚函数的主要用途是实现运行时多态。内联函数用于提高代码效率。每当调用内联函数时,内联函数的代码就会在编译时内联函数调用时被替换。

每当使用基类引用或指针调用虚拟函数时,都不能内联,但是无论何时使用不带该类的引用或指针的对象来调用,都可以内联,因为编译器在编译时就知道该对象的确切类。

范例程式码

#include<iostream>
using namespace std;
class B {
   public:
      virtual void s() {
         cout<<" In Base \n";
      }
};

class D: public B {
   public:
      void s() {
         cout<<"In Derived \n";
      }
};

int main(void) {
   B b;
   D d; // An object of class D
   B *bptr = &d;// A pointer of type B* pointing to d
   b.s();//Can be inlined as s() is called through object of class
   bptr->s();// prints"D::s() called"
   //无法内联,因为通过指针调用了virtualfunction。
   return 0;
}

输出结果

In Base
In Derived