我创建了一个定义二维矢量类型的类模板,其中成员具有可变数据类型。
template<class Type> struct XY
{
Type X, Y;
XY() {}
XY(Type X, Type Y): X(X), Y(Y)
Type Square() const { return (X * X + Y * Y); }
};
此外,我重载了减号运算符并定义了一个额外的S
函数。
template<class Type> XY<Type> operator-(const Type& P, const Type& Q)
{ return XY<Type>(P.X - Q.X, P.Y - Q.Y); }
template<class Type> Type S(const XY<Type>& P, const XY<Type>& Q)
{ return (P - Q).Square(); }
现在下面的代码无法编译,在VS2008下:
void main()
{
struct XY<int> P, Q;
S(P, Q);
}
最让我困惑的是错误消息,说
Error 1 error C2440: 'return' : cannot convert from 'XY<Type>' to 'int'
在定义函数的行S
.
减法的结果显然是一个struct XY
,应用于它的方法Square
返回一个标量,不需要任何转换。
任何解释?
你不是说
template<class Type> XY<Type> operator-(const XY<Type>& P, const XY<Type>& Q)
而不是
template<class Type> XY<Type> operator-(const Type& P, const Type& Q)
后者显然不叫。在函数S
中,编译器尝试调用内置operator -
进行int
,因此尝试将参数转换为P
和Q
转换为int
(这是不可能的,因此会出现错误(。