virtual修饰的函数可以在派生的类中重新定义,可以通过动态分配对象的基类指针实现多借口。
例:
#include<iostream> using namespace std; class A { public: A(int x=0):t(x){} virtual int f() { return t; } private: int t; }; class B:public A { public: B(int x=0,int y=0):A(x),t(y){} int f() { return 10*t; } private: int t; }; int main() { B b(3,2); A *tmp=&b; cout<<tmp->A::f()<<endl; cout<<tmp->f()<<endl; system("pause"); return 0; }
若基类去掉virtual修饰,那么将不具有多接口的作用!
#include<iostream> using namespace std; class A { public: A(int x=0):t(x){} int f() { return t; } private: int t; }; class B:public A { public: B(int x=0,int y=0):A(x),t(y){} int f() { return 10*t; } private: int t; }; int main() { B b(3,2); A *tmp=&b; cout<<tmp->A::f()<<endl; cout<<tmp->f()<<endl; system("pause"); return 0; }