如下测试代码:
#include < iostream >
using namespace std;
class base
... {
public:
base()
...{
cout<<"create base"<<endl;
};
virtual ~base()
...{
cout<<"clean base"<<endl;
};
virtual void foo_1() = 0;
virtual void foo_2();
void foo_3();
} ;
// 实现
void base ::foo_2()
... {
cout<<"virtual base::foo_2"<<endl;
}
void base ::foo_3()
... {
cout<<"isnt virtual base::foo_3"<<endl;
}
// 继承类
class inherit : public base
... {
public:
inherit()
...{
cout<<"create inherit"<<endl;
};
~inherit()
...{
cout<<"clean inherit"<<endl;
};
//virtual void foo_0() = 0;
virtual void foo_1();
virtual void foo_2();
void foo_3();
} ;
// 实现
void inherit::foo_1()
... {
cout<<"virtual inherit::foo_1"<<endl;
}
void inherit::foo_2()
... {
cout<<"virtual inherit::foo_2"<<endl;
}
void inherit::foo_3()
... {
cout<<"isnt virtual inherit::foo_3"<<endl;
}
int main()
... {
base* ptr = new inherit;
ptr->foo_1();
ptr->foo_2();
ptr->foo_3();
delete[] ptr;
int nWait;
cin>>nWait;
return 0;
}
#include < iostream >
using namespace std;
class base
... {
public:
base()
...{
cout<<"create base"<<endl;
};
virtual ~base()
...{
cout<<"clean base"<<endl;
};
virtual void foo_1() = 0;
virtual void foo_2();
void foo_3();
} ;
// 实现
void base ::foo_2()
... {
cout<<"virtual base::foo_2"<<endl;
}
void base ::foo_3()
... {
cout<<"isnt virtual base::foo_3"<<endl;
}
// 继承类
class inherit : public base
... {
public:
inherit()
...{
cout<<"create inherit"<<endl;
};
~inherit()
...{
cout<<"clean inherit"<<endl;
};
//virtual void foo_0() = 0;
virtual void foo_1();
virtual void foo_2();
void foo_3();
} ;
// 实现
void inherit::foo_1()
... {
cout<<"virtual inherit::foo_1"<<endl;
}
void inherit::foo_2()
... {
cout<<"virtual inherit::foo_2"<<endl;
}
void inherit::foo_3()
... {
cout<<"isnt virtual inherit::foo_3"<<endl;
}
int main()
... {
base* ptr = new inherit;
ptr->foo_1();
ptr->foo_2();
ptr->foo_3();
delete[] ptr;
int nWait;
cin>>nWait;
return 0;
}
在VC7下测试:
create base
create inherit
virtual inherit::foo_1
virtual inherit::foo_2
isnt virtual base::foo_3
clean inherit
clean base
从结果中可以得出如下两点结论:
(1)指向派生类的基类指针所调用的虚函数的为派生类中的;
(2)指向派生类的基类指针所调用的类函数(非虚拟函数,非静态函数)为原指针类型所在的函数;
那么可以得知虚函数和非虚函数在类中的布局不一样;
那么基类类型的指针是怎么实现调用非派生类的函数呢?
原因为
每个含有虚函数的类都存在一张虚函数表(vtb),这张虚表是在编译期生成的。
然后每个类的对象都有一个指向虚表的指针,在虚表中可以调用相应的函数。
那么继续分析上面的例子,
由于
base
*
ptr
=
new
inherit;
操作,将产生inherit对象,在inherit的构造函数执行期间,完成inherit的vtb创建过程,同时创建出的inherit中自动产生一个指针指向该vtb。
线面将分别解释上面结论(1)和(2)
由于ptr的地址是指向inherit的对象,但是指针类型依然是基类的。
在调用虚函数时,首先调用指向vtb的指针我们姑且称该指针为ptrVtb,然后通过该函数的索引值来取得vtb中的相对的值。
由于类函数(非虚拟函数,非静态函数)的地址不在类的具体对象中,所以利用ptr调用类函数(非虚拟函数,非静态函数)调用的还是基类的函数!