1:什么多态?
当使用基类的指针或引用调用重写的虚函数时,指向父类调的就是父类的虚函数,指向子类调的就是子类的虚函数。
下面我们来看一段代码
#include<iostream>
using namespace std;
class AA
{
virtual void fun1()
{
cout << "AA::fun(1)" << endl;
}
private:
int _a;
};
class BB
{
void fun2()
{
cout << "AA::fun(1)" << endl;
}
private:
int _b;
};
class CC
{};
int main()
{
cout << sizeof(AA) << endl;
cout << sizeof(BB) << endl;
cout << sizeof(CC) << endl;
system("pause");
return 0;
}
sizeof(AA)的结果为什么会是8呢?这是因为函数fun1是一个虚函数,函数内部存在一个虚表指针。
单继承对象模型
#include<iostream>
using namespace std;
class Base
{
public:
virtual void fun1()
{}
virtual void fun2()
{}
public:
int _a;
};
class Diver:public Base
{
public:
virtual void fun1()
{}
virtual void fun3()
{}
virtual void fun()
{}
public:
int _b;
};
typedef void(*FUNC)();
void PrintVtable(int *Vtable)
{
cout << "虚表地址" << Vtable << endl;
for (int i = 0; Vtable[i] != 0; i++)
{
printf("第%d个虚表的地址->0X%x", i, Vtable[i]);
FUNC f = (FUNC)Vtable[i];
f();
cout << endl;
}
cout << endl;
}
int main()
{
Base b1;
Diver d1;
int *Vtable1 = (int*)(*(int*)&b1);
int *Vtable2 = (int*)(*(int*)&d1);
PrintVtable(Vtable1);
PrintVtable(Vtable2);
system("pause");
return 0;
}
由于编译器做了一定的优化,子类中自己定义的函数在监视窗口看不到,必须要写一个打印的函数才能显示出来
多继承对象模型
多继承是指一个子类继承了两个或两个以上的父类。
class Base1
{
public:
virtual void fun1()
{
cout << "Base1::fun1" << endl;
}
virtual void fun2()
{
cout << "Base1::fun2" << endl;
}
public:
int _a;
};
class Base2
{
public:
virtual void fun1()
{
cout << "Base2::fun1" << endl;
}
virtual void fun2()
{
cout << "Base2::fun3" << endl;
}
int _b;
};
class Diver:public Base1,public Base2
{
public:
virtual void fun1()
{
cout << " Diver::fun1" << endl;
}
virtual void fun3()
{
cout << " Diver::fun3" << endl;
}
virtual void fun4()
{
cout << " Diver::fun4" << endl;
}
public:
int _b;
};
void test()
{
Base1 b1;
PrintVtable(*((int*)&b1));
Base2 b2;
PrintVtable(*((int*)&b2));
Diver d;
PrintVtable(*((int*)&d));
PrintVtable(*((int*)((char*)&d + sizeof(Base1))));
}
在监视窗口无法观察到子类的虚表,借用打印函数我们可以观察到:在多继承对象模型中,子类的虚函数放在先继承的那个虚表里面