您的位置:首页 > 编程语言 > C语言/C++

C++类虚函数表

2016-03-10 15:50 381 查看
#include <iostream>
#include <cstdlib>

using namespace std;

class Base1
{
public:
virtual void f()
{
cout << "Base1 f()" << endl;
}
virtual void g()
{
cout << "Base1 g()" << endl;
}
virtual void h()
{
cout << "Base1 h()" << endl;
}
};
class Base2
{
public:
virtual void f()
{
cout << "Base2 f()" << endl;
}
virtual void g()
{
cout << "Base2 g()" << endl;
}
virtual void h()
{
cout << "Base2 h()" << endl;
}
};
class Base3
{
public:
virtual void f()
{
cout << "Base3 f()" << endl;
}
virtual void g()
{
cout << "Base3 g()" << endl;
}
virtual void h()
{
cout << "Base3 h()" << endl;
}
};
class Base4
{
public:
void f()
{
cout << "Base4 f()" << endl;
}
void g()
{
cout << "Base4 g()" << endl;
}
void h()
{
cout << "Base4 h()" << endl;
}
};
class Child : public Base1, public Base2, public Base3, public Base4
{
public:
void h()
{
cout << "Child h()" << endl;
}
virtual void e()
{
cout << "Child e()" << endl;
}
/*virtual*/ long &getRef()
{
return value;
}
private:
long value;
};

int _tmain(int argc, _TCHAR* argv[])
{
Child c;
cout << sizeof(c) << endl;

typedef void (*FUNC)();
FUNC pFunc;
int **ptrTable = (int **)&c;

cout << &c << endl;
cout << &ptrTable[0] << endl;
cout << &ptrTable[1] << endl;
cout << &ptrTable[2] << endl;
long &value = c.getRef();
cout << &value << endl;

cout << "---------------------------------" << endl;

pFunc = (FUNC)ptrTable[0][0];
pFunc();
pFunc = (FUNC)ptrTable[0][1];
pFunc();
pFunc = (FUNC)ptrTable[0][2];
pFunc();
pFunc = (FUNC)ptrTable[0][3];
pFunc();
// 注意getRef前的virtual修饰符
//pFunc = (FUNC)ptrTable[0][4];
//pFunc();

cout << "---------------------------------" << endl;

pFunc = (FUNC)ptrTable[1][0];
pFunc();
pFunc = (FUNC)ptrTable[1][1];
pFunc();
pFunc = (FUNC)ptrTable[1][2];
pFunc();

cout << "---------------------------------" << endl;

pFunc = (FUNC)ptrTable[2][0];
pFunc();
pFunc = (FUNC)ptrTable[2][1];
pFunc();
pFunc = (FUNC)ptrTable[2][2];
pFunc();

cout << "---------------------------------" << endl;

system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: