在C++中,利用虚函数来可根据初始化的对象指针类型进行调用与之对应的方法,在调用时,直接默认调用基类的方法,如果调用的时其\
它派生类的方法时,又会出现什么问题呢?这里做了一个实验:
基类A声明如下:
- #ifndef _A__H__
-
#define _A__H__
-
-
#include <iostream>
-
using namespace std;
-
-
-
class A
-
{
-
public:
-
virtual void print(void)
-
{
-
cout<<"It's from A!"<<endl;
-
}
-
~A(void)
-
{
-
cout<<"A destructor"<<endl;
-
-
}
-
-
};
-
- #endif
基类派生出两个子类B和C,定义如下:
- #ifndef __B__H__
-
#define __B__H__
-
-
#include <iostream>
-
using namespace std;
-
-
class B:public A
-
{
-
public:
-
void print(void)
-
{
-
cout<<"It's from B!"<<endl;
-
}
-
~B()
-
{
-
cout<<"B's destructor"<<endl;
-
}
-
-
};
-
-
-
- #endif
子类C定义如下:
- #ifndef _C__H__
-
#define _C__H__
-
-
#include <iostream>
-
using namespace std;
-
-
#include "A.h"
-
-
class C:public A
-
{
-
public:
-
void print(void)
-
{
-
cout<<"It's from C!"<<endl;
-
}
-
~C(void)
-
{
-
cout<<"C destructor"<<endl;
-
-
}
-
-
};
-
-
-
- #endif
下面就是测试的main函数了:
- #include "A.h"
-
#include "B.h"
-
#include "C.h"
-
-
#include <iostream>
-
using namespace std;
-
-
typedef void (A::*Afunc_t)(void);
-
typedef void (B::*Bfunc_t)(void);
-
typedef void (C::*Cfunc_t)(void);
-
-
int main(void)
-
{
-
A *pb = new B();
-
A *pc = new C();
-
Afunc_t fa = static_cast<Afunc_t>(&B::print);
-
Afunc_t fc = reinterpret_cast<Afunc_t>(&C::print);
-
(pb->*fc)();
-
-
(pb->*fa)();
-
((*pc).*fc)();
-
//((*pc).*fc)();
-
//pb->print();
-
//pc->print();
-
delete pb;
-
delete pc;
-
-
return 0;
- }
看来还是以指针类型的虚函数为标准.其中,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,