【发布时间】:2013-12-11 07:29:07
【问题描述】:
给定以下教程中的函数模板。
template<class T>
double GetAverage(T tArray[], int nElements)
{
T tSum = T(); // tSum = 0
for (int nIndex = 0; nIndex < nElements; ++nIndex)
{
tSum += tArray[nIndex];
}
// Whatever type of T is, convert to double
return double(tSum) / nElements;
}
排队
T tSum = T(); // tSum = 0
他们说它将调用特定类型的默认构造函数(基于我们调用此函数的类型)。我怀疑这个调用如何将值分配给 tSum,因为这会很好地调用构造函数。但是由于构造函数没有返回任何内容,因此 iSum 如何初始化为 int 的 0 或 double 的 0.0。
【问题讨论】: