在c++中的动态联编是通过虚函数来实现,但在调用时 , 必须用引用、指针才能实现动态联编
例子如下:
指针调用
#include <iostream> using namespace std; const double pi = 3.14; class A { public: A() {}; virtual double area() const {return 0.0;} }; class B:public A { public: B(double myr) {R = myr;} virtual double area() const {return pi*R*R;} private: double R; }; int main() { A *fig; B c(3.0); cout<<"Area of B is "; fig = &c; cout<<fig->area()<<endl; return 0; }
普通变量调用
#include <iostream> using namespace std; const double pi = 3.14; class A { public: A() {}; virtual double area() const {return 0.0;} }; class B:public A { public: B(double myr) {R = myr;} virtual double area() const {return pi*R*R;} private: double R; }; int main() { A fig; B c(3.0); cout<<"Area of B is "; fig = c; cout<<fig.area()<<endl; return 0; }