1.单继承下的虚函数
代码1:
#include <iostream>
#include <stdio.h>
using namespace std;
class Base
{
public:
virtual void f() { cout << "Base::f()" << endl; }
virtual void g() { cout << "Base::g()" << endl; }
virtual void h() { cout << "Base::h()" << endl; }
};
class Derive :public Base {
public:
virtual void i() { cout << "Derive::i()" << endl; }
virtual void g() { cout << "Derive::g()" << endl; }
void myselffunc() {} //只属于Derive的函数
};
int main()
{
Derive myderive;
Derive *pmyderive = &myderive;
pmyderive->f();
pmyderive->g();
pmyderive->h();
pmyderive->i();
}
问题:
在子类中在g()的前面定义了i(),那子类的虚函数表应该是怎样的顺序呢?
反汇编:
可以从上述汇编中发现子类虚函数表中虚函数顺序为:
f(), g(), h(), i()
虚函数表简图:
子类中虚函数表中顺序与父类中排列顺序一致,在后面增加自己的虚函数地址(虚函数表表项),在虚函数表中顺序地记录着每个函数的首地址
代码2:
#include <iostream>
#include <stdio.h>
using namespace std;
class Base
{
public:
virtual void f() { cout << "Base::f()" << endl; }
virtual void g() { cout << "Base::g()" << endl; }
virtual void h() { cout << "Base::h()" << endl; }
};
class Derive :public Base {
public:
virtual void i() { cout << "Derive::i()" << endl; }
virtual void g() { cout << "Derive::g()" << endl; }
void myselffunc() {} //只属于Derive的函数
};
int main()
{
Base *pb = new Derive(); //基类指针指向一个子类对象
pb->g();
//编译器视角
//(*pb->vptr[1])(pb); 使用虚函数表指针调用虚函数表项,传入this指针进行调用虚函数
//在编译期间