首页 > 代码库 > 求1+2+3+。。。+N

求1+2+3+。。。+N

1 通过构造函数

代码:

#include <iostream>
#include <vector>
#include <assert.h>

using namespace std;

class temp{
private :
	static unsigned int N,sum;
public :
	temp(){
		++N;
		sum += N;
	}
    static	void reset(){
		N=0;
		sum=0;
	}
	static int getSum(){
		return sum;
	}

};
unsigned int temp::N = 0;
unsigned int temp::sum = 0;

int main()
{	
	temp::reset();
	temp *a = new temp[3];
	delete [] a;
	a = NULL;
	cout<<temp::getSum()<<" ";
    return 0;
}

2 使用模板元

#include <iostream>using namespace std;template<int N> struct sum{<span style="white-space:pre">	</span>enum value {n = N + sum<N-1>::n};};template <> struct sum<1>{<span style="white-space:pre">	</span>enum value { n= 1};};void main(){<span style="white-space:pre">	</span>int a[sum<4>::n];<span style="white-space:pre">	</span>cout<<sizeof(a) / sizeof( int) <<endl ;}

运行结果:


更多模板元见http://blog.csdn.net/buyingfei8888/article/details/38413031

3 使用函数指针

#include <iostream>using namespace std;typedef unsigned int (*fun) (unsigned int);unsigned int soluation_tem(unsigned int n){<span style="white-space:pre">	</span>return 0;}unsigned int soluation(unsigned int n){<span style="white-space:pre">	</span>static fun f[2] = {soluation_tem,soluation};<span style="white-space:pre">	</span>return n + f[!!n](n-1);}void main(){<span style="white-space:pre">	</span>cout << soluation(3);<span style="white-space:pre">	</span>}

4 使用虚函数:

代码:

#include <iostream>

using namespace std;
class A;
A * Array[2];
class A{
public :
	virtual unsigned int sum(int N){
		return 0;
	}
};

class B :public A{
public:
	virtual unsigned int sum(int N){
		return Array[!!N]->sum(N-1) + N;
	}
};

unsigned int soluation(unsigned int n){
	A a;
	B b;
	Array[0] = &a;
	Array[1] = &b;
	return Array[1]->sum(n);

}

void main(){
	cout << soluation(3);
}