自考新教材-p352_3(2)
源程序:用面向对象方法又做一遍
#include <iostream>
#define N 10
using namespace std;
template <typename T>
class sum_array
{
private:
T a[N];
public:
sum_array(T a1[])
{
for (int i = 0; i < N; i++)
a[i] = a1[i];
}
T cal_sum(T a[], int n)
{
int i, size;
T sum = 0;
cout << "您想求数组前几项的和,请输入:";
cin >> size;
for (i = 0; i < size; i++)
{
sum = sum + a[i];
}
return sum;
}
};
int main()
{
int num[N] = {1,3,5,7,9,2,4,6,8,0};
sum_array <int>suma(num);
int result = suma.cal_sum(num,N);
cout << result << endl;
cout << endl;
double num1[N] = { 1.1,3.3,5.5,7.7,9.9,2.2,4.4,6.6,8.8,0.0 };
sum_array <double>suma1(num1);
double result1 = suma1.cal_sum(num1, N);
cout << result1 << endl;
cout << endl;
/*
char num2[N] = { 'a','c','e','f','h','m','p','b','j','d' };
int result2 = sum_array(num2, N);
cout << result2 << endl;
*/
system("pause");
return 1;
}
运行结果: