1 + 2 + 3 +... + N

Source: Internet
Author: User

1 + 2 + 3 + n

1. Constructor

Code:

#include <iostream>#include <vector>#include <assert.h>using namespace std;class temp{private :static unsigned int N,sum;public :temp(){++N;sum += N;}    staticvoid 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. Use template Meta

#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 ;}

Running result:


For more templates, see http://blog.csdn.net/buyingfei8888/article/details/38413031

3. Use function pointers

#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. Use virtual functions:

Code:

#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);}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.