求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.youkuaiyun.com/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);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值