#include <stdio.h>
#include "iostream"
using namespace std;
class Node;
typedef void (Node::*SEL_SCHEDULE)();
#define schedule_selector(_SELECTOR) (SEL_SCHEDULE)(&_SELECTOR)
class Scheduler
{
public:
Scheduler();
void scheduleSelector(SEL_SCHEDULE selector,Node *node);
public:
static Scheduler* getScheduler();
};
static Scheduler* scheduler = NULL;
Scheduler* Scheduler::getScheduler()
{
if(!scheduler)
{
scheduler = new Scheduler();
}
return scheduler;
}
Scheduler::Scheduler()
{
printf("this is Scheduler ctor\n");
}
void Scheduler::scheduleSelector(SEL_SCHEDULE selector,Node *node)
{
if(node && selector)
{
(node->*selector)();
}
}
class Node
{
public:
void schedule(SEL_SCHEDULE selector,int x);
void schedule(SEL_SCHEDULE selector);
};
void Node::schedule(SEL_SCHEDULE selector,int x)
{
this->schedule(selector);
}
void Node::schedule(SEL_SCHEDULE selector)
{
scheduler->scheduleSelector(selector,this);
}
class A : public Node
{
public:
void fun1();
virtual void fun2();
};
void A::fun1()
{
printf("this is A fun1\n");
// this->fun2();// 第一种方式,输出this is B fun2
// A::fun2();// 第二种方式,输出this is A fun2
// this->A::fun2();// 第三种方式,输出this is A fun2
schedule(schedule_selector(A::fun2),5);// 第四种方式,输出this is B fun2
}
void A::fun2()
{
printf("this is A fun2\n");
}
class B : public A
{
public:
void fun2();
};
void B::fun2()
{
printf("this is B fun2\n");
}
int main()
{
A *a = NULL;
a = new B();
a->fun1();// 测试通过父类的一个非virtual方法去调用virtual方法。第一种方式由于fun2是virtual的,所以调用了B的方法;第二和第三种方式均明确调用的是A作用域下的fun2方法;第四种方式比较特别,虽然传入的是A::fun2,但是经过函数指针SEL_SCHEDULE的转化,在实际调用(node->*selector)();时还是调用的B的fun2方法
return 0;
}
《--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------》
其实理解了上述的方式四,可以把上述代码简化为如下:
#include <stdio.h>
#include "iostream"
using namespace std;
class Node;
typedef void (Node::*SEL_SCHEDULE)();
void testExecute(SEL_SCHEDULE selector,Node *node)
{
if(node && selector)
{
(node->*selector)();
}
}
class Node
{
};
class A : public Node
{
public:
void fun1();
virtual void fun2();
};
void A::fun1()
{
printf("this is A fun1\n");
testExecute((SEL_SCHEDULE)(&A::fun2),this);
}
void A::fun2()
{
printf("this is A fun2\n");
}
class B : public A
{
public:
void fun2();
};
void B::fun2()
{
printf("this is B fun2\n");
}
int main()
{
A *a = NULL;
a = new B();
a->fun1();
return 0;
}
其中testExecute是一个全局函数,而不再属于某一个类
关于纯虚函数
不能在构造或析构中调用