我制作了一个简单的Vector2
模板类,该类用于存储X
和Y
值。现在,我试图在源文件中保留模板的实现,但是由于操作符重载,我无法做到这一点
class Vector2
{
public:
Vector2<Type>();
Vector2<Type>(Type x, Type y);
Vector2<Type>(const Vector2<Type> &v);
~Vector2<Type>();
Vector2<Type> operator+ (const Vector2<Type> &other)
{
return Vector2<Type>(x + other.x, y + other.y);
}
private:
Type x, y;
};
现在,它可以编译并正常工作,但是当前位于头文件中。实现
Vector2
的构造函数和反构造函数也可以很好地工作,但是当我尝试以下操作时:。H:
Vector2<Type> operator+ (const Vector2<Type> &other);
.cpp:
template <class Type>
Vector2<Type>::operator+ (const Vector2<Type> &other)
{
return Vector2<Type>(x + other.x, y + other.y);
}
编译器告诉我:
missing type specifier - int assumed. Note C++ does not support default-int
亲切的问候,我
最佳答案
您对operator +
的定义缺少返回类型:
template <class Type>
Vector2<Type> Vector2<Type>::operator+ (const Vector2<Type> &other)
// ^^^^^^^^^^^^^
{
return Vector2<Type>(x + other.x, y + other.y);
}
还应注意,除非您对所有本来会隐式创建的实例使用显式实例化,否则类模板的成员函数的定义应出现在包含类模板定义的同一 header 中。
关于c++ - 源文件而不是 header 中的模板运算符重载,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16287178/