面试题:
实现函数void f(int a, int b, int c),编码中不允许出现任何if,switch,for,while之类的关键词以及“?:”表达式,并要求:a=1时,打印b+c的值;a=2时,打印b-c的值;a=3时,打印b*c的值;a=4时,打印b/c的值;a=5时,打印b的阶乘加上c的阶乘;(不用考虑传入的a,b,c的值域错误所导致的异常结果或者崩溃)。
解法一:
class CBase
{
public:
virtual void show(int b, int c)=0;
};
class CDerived1:public CBase //继承的时候注意些public
{
public:
virtual void show(int b, int c)
{
cout<< b+c<<endl;
}
};
class CDerived2:public CBase
{
public:
virtual void show(int b, int c)
{
cout<< b-c<<endl;
}
};
class CDerived3:public CBase
{
public:
virtual void show(int b, int c)
{
cout<<b*c<<endl;
}
};
class CDerived4:public CBase
{
public:
virtual void show(int b, int c)
{
cout<< b/c<<endl;
}
};
CBase *p[]={new CDerived1(), new CDerived2(), new CDerived3(), new CDerived4()};
void f(int a, int b, int c)
{
p[a-1]->show(b,c);
}
int main()
{
f(1,2,3);
f(2,2,3);
f(3,2,3);
f(4,2,3);
return 0;
}
解法二:
函数指针数组和子类数组有点类似,函数指针可以看做c语言实现c++多态的一种方式
#include <iostream>
using namespace std;
void add(int b,int c)
{
cout<<b+c<<endl;
}
void minus(int b,int c)
{
cout<<b-c<<endl;
}
void (*p[2])(int b,int c); //函数指针
void f(int a, int b, int c)
{
(*p[a-1])(b,c);
}
int main()
{
p[0] = add;
p[1] = minus;
f(1,2,3);
f(2,2,3);
return 0;
}
解法三:采用异或的方式 ^ 和 并&& 的性质
void f(int a, int b, int c)
{
int sum;
(!(a ^ 1) && printf("%d\n", b + c));
(!(a ^ 2) && printf("%d\n", b - c));
(!(a ^ 3) && printf("%d\n", b*c));
(!(a ^ 4) && printf("%d\n", b / c));
}