64,649
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
using namespace std;
class Base
{
public:
virtual void f() { cout << "f" << endl; }
virtual void g() { cout << "g" << endl; }
private:
};
int main()
{
typedef void(*Fun)(void);
Base b;
Fun pFun = NULL;
pFun = (Fun)*((long*)*(long*)(&b));
pFun();
system("pause");
return 0;
}
#include <cstring>
#include <iostream>
using namespace std;
class Base
{
public:
Base():i(100)
{
memset(j,'a',10);
j[9]=0;
}
virtual ~Base()
{
}
virtual void f()
{
cout <<i<< "f:"<<j << endl;
j[8]='b';
}
virtual void g()
{
cout <<i<< "g:"<<j << endl;
}
private:
int i;
char j[10];
};
int main()
{
typedef void(*Fun)(Base *);
Base b;
Fun pFun = NULL;
pFun = (Fun)*(((long*)*(long*)(&b))+2);//invoke f()
pFun(&b);
pFun = (Fun)*(((long*)*(long*)(&b))+3);//invoke g();
pFun(&b);
return 0;
}
Base类中的成员函数采用的是thiscall的调用约定,默认都要向f()、g()传一个this指针;具体地去搜一下thiscall吧;
上面的代码我在linux 使用g++4.8.5编译通过,运行正常//char (*(*x[3])())[5];//x是什么类型的变量?
//
//分析C语言声明,关键是搞清楚这个变量是个什么东西(函数、指针、数组),
//是函数那么剩下的就是他的参数和返回值,
//是指针那剩下部分是说明他指向什么,
//是数组剩下的部分就是说明数组的成员是什么类型。
//解析C语言声明规则:
//从左侧第一个标识符开始,按照优先级进行结合。*表示是..的指针,const表示只读的,volatile表示可变的,[]表示是数组,()表示是函数。
//
//x和[3]结合说明是一个大小为3的数组,该数组的每个元素为一类指针,该类指针指向一类函数,该类函数无参数,返回一类指针,该类指针指向一个大小为5的char型数组
#include <stdio.h>
#include <typeinfo.h>
char num[5];
char (*x00())[5] {
return #
}
int main() {
char (*(*x[3])())[5];//是个数组,大小为3
char (*(*x0 )())[5];//数组的元素,是个函数指针
char (*( x00 )())[5];//函数原型,参数为空,返回值为指针
char (* x000 )[5];//返回值
x0 = x00;
x[0] = x0;
x[1] = x0;
x[2] = x0;
printf("typeid(x).name() is %s\n",typeid(x).name());
return 0;
}
//typeid(x).name() is char (* (__cdecl**)(void))[5]