一道Apple公司(中国)的面试题目

Apple在中国(上海)有公司业务,但是感觉主要是做测试工作的部门,主要是保障Apple的产品质量QE。面试的时候,面试官出了一道题目,我貌似曾今开过类似的题目,但是由于当场发挥不佳没有答出来。题目大意是这样的:

在公司的某个通信协议中存在这样一个场景,甲给乙发送了一个数据帧,这个数据帧最前面的一个字节代表是数据帧的类型(总共四种),只可能为0,1,2,3。甲每次给乙发送一个数据包后,乙要通过自己写程序调用对应数据帧类型的函数来对这个数据帧进行处理。处理函数必须要和帧相对应,不然得不到真确的结果。要求不能使用if...else...,switch和三目表达式语句。

题目到这里,想必大家都已经知道可以使用C++的虚函数来做,可是到底应该怎么写呢?下面给出一种实现方法。

#include <iostream>
using namespace std;
typedef void (*pFunc)(void);
class Solution{
public:
virtual void func1(){ cout << "func1 executed ..." << endl;}
virtual void func2(){ cout << "func2 executed ..." << endl;}
virtual void func3(){ cout << "func3 executed ..." << endl;}
virtual void func4(){ cout << "func4 executed ..." << endl;}
void doSomething(int frame_id) {
if(frame_id >= && frame_id <=){
pFunc pf;
pf = (pFunc)*((int *)*(int *)this + frame_id);
pf();
}
}
}; int main(){
Solution sln;
sln.doSomething();
sln.doSomething();
sln.doSomething();
sln.doSomething();
return ;
}

执行结果如下:

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAkUAAACzCAIAAAAISP+7AAAQT0lEQVR4nO3da28cVx3H8XmC4KXkNeQdIMRNi4AKVUQ8iChCSDxBMgIhQKiX0Da9ibaw4KaUlqitlVSklzTOOGkfULtSHepCCeBuIbXV+JYLTkJVDQ/cnT1zLv85M3Nmd/b4+1EU7Z49cy4z6/PzzK53kwwAgOk0t7j+/lAy6cEAAFDT3OL6f4bIMwDAtJpbXP9giDwDAEyrucX1XEmeLV94O1047/PvreULH3/88XgmAABAlmVzi+sfDpXk2XNzLyy9tbL01tvGv5U3l1feXF45+fK5ky8tnHxp4Q/Hn9/Y2BjPBAAAyLJsbnF9Y6gkz+YXXrt569aNmyX/bt66dXp+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OuaNKXfuPUN7DQk25sLQF124XDpnPMfLpSL2hjdOzC22mVatZN3TtkMTxRPIZqmc1IBS+zzNmodYR1iMA3UeeAQBiQJ4BAGJQ//0gO0cPzk569AAA7OHz9QEAMSDPAAAxIM90++3txftqsgAixvefWUQzER/7arIAIsb3xVi0N4vJ7p84jg4AWJFnFuQZAEydKfj+s9JVWKtm7docktCsq5q1I/825WnKc0zK9pIwd1fvrtYS264zb1caPAC0bZq+/8zKtbnZVI02XZvUaNNap/k0rYXWCq4uhKMW6hgBwBiM+/vPrOFn/R2/0i/+WptyDpU2a60mDN6nTXMwwjhLNxQ2F9r0zDPPNl07BAAmYmLf5+lTv3QTrU7APDPXaHma+zPP3OMFgHHr1vdT+yzKtdv0ac2znRptlm4Yapqt5pka866a5ByAiQj292dqo2mR9SFrZbnQJXVwdefZWmKszq4h+a/gwkxrbGsWls7dWtm6ibVyYkSatYvyHQEAodXLs1MLSTKbJLOTHn0Nbay2rOAAMHH1P18/y7LB4UkP35v/adBk2wQA1MP3nwEAYkCeAQBiQJ4BAGJAngEAYlD//SA7Rw/OTnr0AADs4fs8AQAxIM8AADEgzwAAMSDPAAAxIM8AADEgzwAAMSDPAAAxIM8AADEgzwAAMQj2fZ7aN0MCADBO5BkAIAbkGQAgBuQZACAGvB8EABAD8gwAEAPyDAAQA/IMABAD8gwAEAPyDAAQA/IMABAD8gwAEAPyDAAQA/IMABAD8gwAEAPyDAAQA/IMABAD8gwAEAPyDAAQA/IMABAD8gwAEAPyDAAQA/IMABAD8gwAEAPyDAAQA/IMABAD8gwAEIOGefZ/qzW2Cylw0F4AAAAASUVORK5CYII=" alt="" />

其中关于如何获取指向虚函数的指针的方法,可以参见文章:http://www.cppblog.com/xczhang/archive/2008/01/20/41508.html

上一篇:.Net魔法堂:提取注释生成API文档


下一篇:一道算法题目, 二行代码, Binary Tree