虚函数 多态

/*用虚函数实现动态连接在编译期间,C++编译器根据程序传递给函数的参数或者
函数返回类型来决定程序使用那个函数,然后编译器用正确的的函数替换每次启动。
这种基于编译器的替换被称为静态连接,他们在程序运行之前执行。另一方面,当程序
执行多态性时,替换是在程序执行期进行的,这种运行期间替换被称为动态连接。
如下例子:*/
#include<iostream>
using namespace std;
//类声明及成员函数定义
class A{
public:
 virtual void f(){cout << "A::f" << endl;};
};

class B:public A{
public:
 virtual void f(){cout << "B::f" << endl;};
};
class C:public A{
public:
 virtual void f(){cout << "C::f" << endl;};
};
//函数定义
void test(A *a){
 a->f();
};
//主函数
int main()
{
 B *b=new B;
 C *c=new C;
 char choice;
 do{
  cout<<"type b for class B,c for class C:"<<endl;
  cin>>choice;
  cout<<"choice="<<choice<<endl;
  if(choice=='b') test(b);
  else if(choice=='c') test(c);
 }while(1);
 cout<<endl<<endl;
 return 0;
}

posted on 2009-04-06 18:07  TobyLin的学习之路  阅读(166)  评论(0编辑  收藏  举报

导航