C++ 面试题

面试题:

实现函数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));
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值