# 求1+2+....+n

34人阅读 评论(0)

题目：



1.构造函数
2.虚函数
3.函数指针
4.模板类型


1.构造函数：

class Temp
{
public:
Temp() { ++N; Sum += N; }
static void Reset() { N = 0; Sum = 0; }
static unsigned int GetSum() { return Sum; }

private:
static unsigned int N;
static unsigned int Sum;
};

unsigned int Temp::N = 0;
unsigned int Temp::Sum = 0;

class Solution
{
public:
int Sum_Solution( int n )
{
Temp::Reset();
Temp* a = new Temp[n];
delete []a;
a = NULL;

return Temp::GetSum();
}
};

int main( void )
{
Solution sos;
cout << sos.Sum_Solution( 100 ) << endl;
return 0;
}

2.虚函数

class A;
A* Array[2];

class A
{
public:
virtual unsigned int Sum( unsigned int n )
{
return 0;
}
};

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

class Solution
{
public:
int Sum_Solution( int n )
{
A a;
B b;
Array[0] = &a;
Array[1] = &b;

int value = Array[1]->Sum(n);
return value;
}
};

int main( void )
{
Solution sos;
cout << sos.Sum_Solution( 100 ) << endl;
return 0;
}

3.函数指针

typedef unsigned int (*fun)( unsigned int );

unsigned int Solution3_Teminator( unsigned int n )
{
return 0;
}

unsigned int Sum_Solution3( unsigned int n )
{
static fun f[2] = { Solution3_Teminator, Sum_Solution3 };
return n + f[!!n]( n-1 );
}

int main( void )
{
cout << Sum_Solution3( 100 ) << endl;
return 0;
}

4.模板类型

template<unsigned int n> struct Sum_Solution4
{
enum Value{
N = Sum_Solution4<n-1>::N + n
};
};

template<> struct Sum_Solution4<1>
{
enum Value { N = 1 };
};

int main( void )
{
cout << Sum_Solution4<100>::N << endl;
return 0;
}
0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：16438次
• 积分：1115
• 等级：
• 排名：千里之外
• 原创：98篇
• 转载：3篇
• 译文：0篇
• 评论：7条
阅读排行
评论排行
最新评论