#include <iostream>
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; }
virtual void print() { cout << "Base" << endl; }
private:
virtual void func1() { cout << "Base:private_func1" << endl; }
};
class c1:public Base
{
public:
virtual void f() { cout << "c1:f()" << endl; }
virtual void f(int a) { cout << "c1:f(int a) = " << a << endl; }
virtual void cvf() { cout << "cvf()" << endl; }
virtual void print() { cout << "C" << endl; }
};
void hello() {
cout << "hello 函数" << endl;
}
void printVirtualTable(Base& a);
typedef void(*Fun)(); //函数指针
int main() {
c1 c;
Base b;
c.cvf();
c.f();
c.f(2);
c.g();
b.f();
// b.f(1);//父类不可以调用子类重载的虚函数,更不可能调用子类的新函数
/* cout << "b虚表" << endl;
printVirtualTable(b);*/
//cout << "c虚表" << endl;
//printVirtualTable(c);
cout << "***********"<<endl;
//Fun vtb = (Fun) * ((int64_t*)*(int64_t*)&b +1);
//vtb();
//cout << "((Fun**)(&b))[0][0]:" << endl;
//((Fun**)(&b))[0][0](); //
cout << "静态多态" << endl;
c1 c2;
Base &b2 = c2;
Base* pb = &c2;
b2.print();//print不是虚函数,则取决于调用者在定义时候的类型,而不是运行时候的=&c2,或者c2
//pb->print(); //加上virtual后,则是动态多态,即print是取决于所给定的类型
//c2.print();
cout << "子类访问父类私有虚函数" << endl;
c1 c3;
//printVirtualTable(c3);
//c3.print();
//c3.func1();
/* Fun pcfun = (Fun) * ((int64_t*)*(int64_t*)(&c3) + 4);
pcfun();*/
((Fun**)(&c3))[0][4](); //((func**)(&a))[0] 代表对象 a 的内存空间中的第一个元素:指向虚函数表的指针;((func**)(&a))[0][0] 表示虚函数表中第一个函数名;
return 0;
//Fun pFun = NULL;
//cout << "虚函数表的地址:" << (int*)(&b) << endl; //b地址强转为int*类型
//cout << "&b = " << &b << endl;
//cout << "虚函数表:第一个函数地址:" << (int*) *(int*)(&b) << endl;
//printVirtualTable(b);
/*int (*helloADD)(void) = (int(*)(void))(&hello);
int x = helloADD();*/
}
void printVirtualTable(Base& a)
{
cout << "虚表实际是指针数组, 位于实例的上方,主要是为保证虚函数表性能最高" << endl;
Fun vtb = (Fun) * (int64_t*)*(int64_t*)&a;
int i = 0;
while (vtb!=NULL)
{
cout << "VirualFunction: " << ++i << endl;
cout << "---->";
vtb();
vtb = (Fun) * ((int64_t*)*(int64_t*)&a + i);
}
}
虚函数+函数指针+虚表+多态
最新推荐文章于 2024-08-03 22:31:51 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)