以下代码可能需要一定的c/c++基础。
需要有一些函数指针的知识
common.h
#pragma once
typedef int (*pt)(void);
void init_2();
2.cpp
#include <iostream>
#include "common.h"
using namespace std;
static pt next_pt;
extern pt top_pt;
int filter_2()
{
cout<<"filter_2"<<endl;
if(next_pt)
next_pt();
}
static void filter_2_init()
{
next_pt = top_pt;
top_pt = filter_2;
}
void init_2()
{
filter_2_init();
}
1.cpp
#include <iostream>
#include "common.h"
using namespace std;
static pt next_pt;
pt top_pt;
static int filter_1()
{
cout<<"filter_1"<<endl;
if(next_pt)
next_pt();
}
static void filter_init()
{
next_pt = top_pt;
top_pt = filter_1;
}
void init_1()
{
filter_init();
}
int main()
{
init_1();
init_2();
top_pt();
return 0;
}
g++ 1.cpp 2.cpp -g -O0
执行
./a.out
filter_2
filter_1
如果你已经编程并执行成功,请继续往下看.
top_pt 为全局变量
next_pt为局部全局变量
top_pt 在每次代码执行时都会变化,不断地指向新的链表头部,通过init_*函数的不断执行,一条链表就产生了。看起来就像是用全局变量组成了一条单项链表。
好吧,又是奇淫技巧,如是而已!