0
#include<cstdlib>
#include<iostream>
#include<math.h>
#include<string>
using namespace std;
class getAverage{
public:
template<class add>
add computeAverage(add input[], int nosOfElem){
add sum = add();//calling default constructor to initialise it.
for(int index=0;index<=nosOfElem;++index){
sum += input[index];
}
return double(sum)/nosOfElem;
}
template<class looptype>
looptype* returnArray(int sizeOfArray){
looptype* inputArray= (int*)malloc(sizeof(int)*sizeOfArray);
for(int index=0;index<=sizeOfArray;++index){
inputArray[index]=index;//=rand() % sizeOfArray;
}
return inputArray;
}
};
int main(){
int sizeOfArray=2;
int inputArray;
getAverage gA;
int* x= gA.returnArray(sizeOfArray);
for(int index=0;index<=2;++index){
cout<<x[index];
}
cout<<endl;
cout<<gA.computeAverage(x,sizeOfArray);
free(x);
return 0;
}
我想创建一个模板函数,通过它我可以创建不同类型的动态数组(int,long,string ..等等)。我试过这样做,并意识到“looptype”永远不会获得类型值。有人可以建议一种方法来做到这一点。无法推导出模板参数'looptype'
感谢
为什么不'自动?还有什么'malloc'在C++代码中做什么?绝对最少使用'new []',但更好的办法是使用'std :: vector',这是一个容器,它有方法来产生大小,而不必传递C风格的指针和大小对。 – tadman