intArray1 = intArray1*2.5;
我猜 intArray1 的类型是 NumericArray<int> 。如果是这样,那么T 就是int。所以在上面的表达式中,2.5 是一个double 将被转换为int,因为它作为参数传递给重载的operator*(const int&)。
这也意味着,2.5 (double) 变成 2 (int) 而factor 基本上是2。数据丢失!
解决此问题的一种方法是将函数模板(作为类模板的成员)用作:
template<class T> //this is for class templatwe
template<class U> //this is for function template
NumericArray<T> NumericArray<T>::operator * (const U& factor) const
{ //^^^^^^^ it is U now!
//your code
}
不要对上述定义中template 的两次用法感到惊讶。 cmets 说他们的目的。如果你理解得很好,那么你也明白参数 now 是U 而不是T,它可以独立于T,因此它可以是你传递给它的任何东西争论。在传递参数时不会丢失数据。
既然你知道int 和double 的乘积结果是double,那么为什么在你将double 传递给它的情况下从函数中返回NumericArray<int>?如果参数是double,我认为返回NumericArray<double> 更有意义。所以下面的似乎是正确的实现:
template<class T> //this is for class templatwe
template<class U> //this is for function template
NumericArray<U> NumericArray<T>::operator * (const U& factor) const
{ //^^^ CHANGED
NumericArray<U> newArray(Size()); //CHANGED HERE TOO!
for (int i = 0; i < Size(); i++)
newArray[i] = factor * GetE(i);
return newArray;
}
等等!现在这正确吗?如果T 是double 而U 是int 怎么办?上面的问题和上一个完全一样!
所以这是第三次尝试:
template<class T> //this is for class templatwe
template<class U> //this is for function template
NumericArray<decltype(std::declval<T>() * std::declval<U>())>
NumericArray<T>::operator * (const U& factor) const
{
typedef decltype(std::declval<T>() * std::declval<U>()) R; //define R
NumericArray<R> newArray(Size()); //CHANGED HERE!
for (int i = 0; i < Size(); i++)
newArray[i] = factor * GetE(i);
return newArray;
}
所以返回类型是:
NumericArray<R>
R 在哪里:
decltype(std::declval<T>() * std::declval<U>());
这取决于T 和U 的产品类型。现在是正确的,至少好多了。
希望对您有所帮助。