不废话,贴代码
主函数随便写的,大佬轻喷,若有高见评论区回复。
#include <iostream>
using namespace std;
/*
若在外表达则需要
template<typename T>//表达错误,数组应作为类中的成员
Array<T>::Array(int n){} 1.表明作用域 2.记得带头 3.数组记得用指针来new
*/
template<typename T>//此处的class也可变更为typename;
class Array
{
public:
//之前是此处的n出现了问题
Array(int n)//类定义,申请相应的空间
{
if (n > 1)
size = n;
else
size = 1;
element = new T[size];
}
~Array()//删除空间
{
delete[] element;
}
void initial()//数组初始化
{
for (int i = 0; i < size; i++)
{
element[i] = 0;
}
}
void input()//输入数据
{
for (int i = 0; i < size; i++)
{
cin >> element[i];
}
}
T add()//进行自身累加,用ans输出
{
ans = 0;
for (int i = 0; i < size; i++)
{
ans += element[i];
}
return ans;
}
double average()//计算平均值,记得用double
{
double n1 = size;//先转换为double进行计算!!!
return add() / n1;//利用前面计算的结果顺便一除
}
void show()
{
for (int i = 0; i < size; i++)
{
cout << element[i] << " ";
}
cout << endl;
}
protected:
int size;
T * element;
T ans = 0;
};
int main()
{
int n, jud = 1;
cout << "请问您想要生成什么类型的数组1.int 2.double 3.long long(_int64)" << endl;
cin >> jud;
cout << "请输入数组大小" << endl;
cin >> n;
switch (jud)
{
case 1:
{
Array<int> a1(n);
a1.initial();
cout << "请输入数组内容" << endl;
a1.input();
cout << "数组的和为:" << a1.add() << endl;
cout << "数组的平均数为 " << a1.average() << endl;
cout << "显示数组 " << endl;
a1.show();
break;
}
case 2:
{
Array<double> a1(n);
a1.initial();
cout << "请输入数组内容" << endl;
a1.input();
cout << "数组的和为:" << a1.add() << endl;
cout << "数组的平均数为 " << a1.average() << endl;
cout << "显示数组 " << endl;
a1.show();
break;
}
case 3:
{
Array<long long> a1(n);
a1.initial();
cout << "请输入数组内容" << endl;
a1.input();
cout << "数组的和为:" << a1.add() << endl;
cout << "数组的平均数为 " << a1.average() << endl;
cout << "显示数组 " << endl;
a1.show();
break;
}
default:
cout << "请输入正确的选项" << endl;
break;
}
return 0;
}