函数指针是发源于C语言的。是在C语言中实现多态的手段
#include <iostream> typedef int (*calculate)(int a, int b); int add(int a, int b); int sub(int a, int b); int cal(int a, int b, calculate cal); int main() { std::cout << "Hello, World!" << std::endl; int result = cal(1, 2, add); std::cout << result << std::endl; return 0; } int add(int a, int b){ return a+b; } int sub(int a, int b){ return a-b; } int cal(int a, int b, calculate cal){ return cal(a, b); }这里仅限于参数个数、类型、返回值类型都是一样的函数的多态。
C++中的多态是通过虚函数来实现的,只要类中有虚函数或是继承至一个带有虚函数的类就会有虚函数表。每一个类的实例都会存储一个虚函数表的指针。对于一个类虚函数表是同一个。
class Base { public: int m_data1; int m_data2; virtual void f() { cout << "Base::f" << endl; } virtual void g() { cout << "Base::g" << endl; } virtual void h() { cout << "Base::h" << endl; } void j(){cout << "Base::j" << endl; } }; class Derived : public Base { public: int m_data3 virtual void f() { cout << "Derived::f" << endl; } void j(){cout << "Devired::j" << endl; } };这里的非虚函数是在编译时就会决定调用的是哪一个函数。
虚继承的引入把对象的模型变得十分复杂,除了每个基类(MyClassA和MyClassB)和公共基类(MyClass)的虚函数表指针需要记录外,每个虚拟继承了MyClass的父类还需要记录一个虚基类表vbtable的指针vbptr
java当中的方法只有final,static,private和构造方法是前期绑定。
动态绑定的过程: 虚拟机提取对象的实际类型的方法表;
虚拟机搜索方法签名;
调用方法。