题目要求:要求不能使用乘除法、for、while、if、else、switch、case等关键字以及条件判断语句(A?B:C)
解法一:
求n个数的累加和就是让累加n次。我们可以在一个类中定义静态变量,然后用构造函数来操作这个变量,然后输出结果。那怎么能让构造函数不用循环和递归操作n次呢,我们于是想到定义数组,这样就会连续调用n次构造函数,以实现我们的目的,代码如下:
#include<iostream>
using namespace std;
class Test
{
public:
Test()
{
sum += n;
n++;
}
static int sum;
static int n;
};
int Test::n = 1;
int Test::sum = 0;
int main()
{
Test* test = new Test[5];
cout << Test::sum << endl;
return 0;
}
解法二:
我们还可以用虚函数来解决这个问题,定义一个类和类中的虚函数,让另一个类去继承
#include<iostream>
using namespace std;
class B
{
public:
virtual int sum(int n)
{
return 0;
}
};
B *array[2];
class C : public B
{
public:
int sum(int n)
{
//对一个数!之后就变成0,再一次取反就变成1
return n + array[!!(n-1)]->sum(n-1);
}
};
int main()
{
B b;
C c;
array[0] = &b;
array[1] = &c;
cout << c.sum(5) << endl;
}
解法三:
把上边的思路拓展一下,我们可以想到用函数指针,也是定义一个数组
#include<iostream>
using namespace std;
int (*ptr[2])(int); //定义一个函数指针数组
int fun1(int n)
{
return 0;
}
int fun2(int n)
{
return n + ptr[!!(n-1)](n-1);
}
//下面这几句在主函数中
int main()
{
ptr[0]=fun1;
ptr[1]=fun2;
cout << fun2(5) << endl;
return 0;
}
解法四:
用函数模板,以及模板特化
#include<iostream>
using namespace std;
template <int n>
struct D
{
enum sum {N=D<n-1>::N+n};
};
template <>
struct D<1>
{
enum sum{N=1};
};
int main()
{
cout << D<5>::N << endl;
return 0;
}
用类模板的另外一种实现方式
#include <iostream>
using namespace std;
template <int N>
class Test :public Test<N - 1> {
public:
int sum;
Test() : sum(N + Test<N - 1>::sum) {}
};
template<>
class Test<0> {
public:
int sum;
Test() : sum(0){}
};
int main() {
Test<5> t;
cout << t.sum << endl;
}