#include <iostream>
using
namespace std;
class
Base
{
public
:
virtual ~Base
(
)
;
virtual void fun
(
)
;
}
;
Base
:
:
~Base
(
)
{
}
void Base
:
:
fun
(
)
{
cout
<
<
"call fun in the base class"
<
<
endl;
}
class
Dervied
:
public Base
{
public
:
virtual ~Derived
(
)
;
virtual void fun
(
)
;
}
;
Derived
:
:
~Derived
(
)
{
}
void Dervied
:
:
func
(
)
{
cout
<
<
"call fun in the Derived"
<
<
endl;
}
int
main
(
)
{
Derived der_one;
Base
*
pd
=
&
der_one;
pd
-
>
fun
(
)
;
/
/
调用的是derived
:
:
fun
(
)
Base bObject
=
der_one;
bObject.fun
(
)
;
/
/
调用的是Base
:
:
fun
(
)
;
cout
<
<
*
(
int
*
)
(
&
der_one
)
<
<
endl;
/
/
是派生类derived的虚函数表的地址
cout
<
<
*
(
int
*
)
(
p
)
<
<
endl;
/
/
是派生类derived的虚函数表的地址
cout
<
<
*
(
int
*
)
(
&
bObeject
)
<
<
endl;
/
/
是基类Base的虚函数表的地址;
/
/
可以发现对于同一种含有虚函数的类的对象共享虚函数表
Derived der_two;
cout
<
<
*
(
int
*
)
(
&
der_one
)
<
<
endl;
cout
<
<
*
(
int
*
)
(
&
der_two
)
<
<
endl;
return
0
;
}
从代码中,我们可以看见,为什么指向派生类对象的指针和引用能实现多态效果,而通过用派生类对象初始化的基类对象调用虚函数而不能实现多态的效果?实质上就是虚函数表的地址入口不一样导致的,通过指向派生类对象的指针和引用能进入派生类对象的虚函数表的地址入口,而用派生类对象初始化的基类对象进入的是基类对象的虚函数表的地址入口。而且很能看清楚对于同一种含有虚函数的类的对象共享虚函数表。