通过一个实例来分析C++中虚函数的调用原理
虚函数是C++中一个重要的概念,搞清楚这个概念对于理解C++运行的内在机制有一定的帮助。下面通过一个例子来总结一下C++中虚函数的调用原理。
示例代码:
#include <iostream>#include <cstdlib>using namespace std;class A{ public: void set(int i,int j) { x=i; y=j; } virtual int get() { return x+y; } private: int x; int y;};class B:public A{ public: void set(int i,int j) { x=i; y=j; } int get() { return x+y; } private: int x; int y;};int main(int argc,char *args[]){ B b; b.set(4,6); B &rb=b; cout<<rb.get()<<endl; A a; a.set(7,8); cout<<a.get()<<endl; A &ra=b; cout<<ra.get()<<endl; system("pause"); return EXIT_SUCCESS; }