Chinaunix首页 | 论坛 | 博客
  • 博客访问: 480461
  • 博文数量: 72
  • 博客积分: 1851
  • 博客等级: 上尉
  • 技术积分: 1464
  • 用 户 组: 普通用户
  • 注册时间: 2010-09-16 17:50
文章分类

全部博文(72)

文章存档

2013年(1)

2012年(17)

2011年(51)

2010年(3)

分类: C/C++

2012-02-25 12:12:06

在C++中,利用虚函数来可根据初始化的对象指针类型进行调用与之对应的方法,在调用时,直接默认调用基类的方法,如果调用的时其\
   它派生类的方法时,又会出现什么问题呢?这里做了一个实验:
基类A声明如下:
  1. #ifndef _A__H__
  2. #define _A__H__

  3. #include <iostream>
  4. using namespace std;


  5. class A
  6. {
  7. public:
  8.    virtual void print(void)
  9.   {
  10.     cout<<"It's from A!"<<endl;
  11.   }
  12.    ~A(void)
  13.    {
  14.      cout<<"A destructor"<<endl;
  15.      
  16.    }
  17.    
  18. };

  19. #endif
基类派生出两个子类B和C,定义如下:
  1. #ifndef __B__H__
  2. #define __B__H__

  3. #include <iostream>
  4. using namespace std;

  5. class B:public A
  6. {
  7. public:
  8.   void print(void)
  9.   {
  10.     cout<<"It's from B!"<<endl;
  11.   }
  12.   ~B()
  13.   {
  14.           cout<<"B's destructor"<<endl;
  15.   }
  16.   
  17. };

  18.   

  19. #endif
子类C定义如下:
  1. #ifndef _C__H__
  2. #define _C__H__

  3. #include <iostream>
  4. using namespace std;

  5. #include "A.h"

  6. class C:public A
  7. {
  8.  public:
  9.  void print(void)
  10.   {
  11.     cout<<"It's from C!"<<endl;
  12.   }
  13.  ~C(void)
  14.  {
  15.    cout<<"C destructor"<<endl;
  16.    
  17.  }
  18.  
  19. };



  20. #endif
下面就是测试的main函数了:
  1. #include "A.h"
  2. #include "B.h"
  3. #include "C.h"

  4. #include <iostream>
  5. using namespace std;

  6. typedef void (A::*Afunc_t)(void);
  7. typedef void (B::*Bfunc_t)(void);
  8. typedef void (C::*Cfunc_t)(void);

  9. int main(void)
  10. {
  11.   A *pb = new B();
  12.   A *pc = new C();
  13.   Afunc_t fa = static_cast<Afunc_t>(&B::print);
  14.   Afunc_t fc = reinterpret_cast<Afunc_t>(&C::print);
  15.   (pb->*fc)();
  16.   
  17.   (pb->*fa)();
  18.   ((*pc).*fc)();
  19.   //((*pc).*fc)();
  20.   //pb->print();
  21.   //pc->print();
  22.   delete pb;
  23.   delete pc;
  24.   
  25.   return 0;
  26. }
看来还是以指针类型的虚函数为标准.其中,C++2010标准中描述如下:
Note:the interpretation of the call of a virtual function depends on the type of the object for which it is called(
   the dynamic type),whereas the interpretation of a call of a non-virutal member function depends only on the type of the pointer or references denoting that object(static type).

参考资料:
1.C++ standard,
2.C++ FAQ, 
阅读(1370) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~