模板操作符在源文件而不是头文件中重载
Template operator overload in source file instead of header
我做了一个简单的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
Kind regards, Me
您对operator +
的定义缺少返回类型:
template <class Type>
Vector2<Type> Vector2<Type>::operator+ (const Vector2<Type> &other)
// ^^^^^^^^^^^^^
{
return Vector2<Type>(x + other.x, y + other.y);
}
还要注意,类模板的成员函数的定义应该出现在包含类模板定义的同一个头文件中,除非您对所有实例化使用显式实例化,否则将隐式创建(参见关于StackOverflow的问题& a)。
相关文章:
- .h 文件中<<运算符重载
- 如何重载 << 运算符,以便将对象的数据写入文件?
- 包括来自另一个文件的运算符重载
- 如何让 + 重载在另一个文件C++中被识别?
- 如何在C++中包含头文件时错误地重载
- C++头/实现文件中的默认和重载构造函数?
- 从文件重载运算符>>读取单词
- 如何重载流运算符以使用位于不同文件中的函数
- 将单独的头文件和类定义文件链接到主函数文件 - G++ 返回重载"undefined reference to"构造函数
- 重载>>运算符以读取文本文件
- 重载 .h 文件中的'+'运算符,链接器错误
- 堆重载的2-D矩阵和c++中的读取文件
- C++头/实现文件和重载运算符
- 重载内存映射文件加载程序(C++)
- 重载运算符 '=' 和 [] 以写入文件中的位置
- 如何处理dervied类的多个重载,而不需要对其他文件进行多次更改
- 文件的 C++ 重载运算符 []
- 有关重载用于读取文本文件的输入运算符>>的问题
- 重载要输出到文件中的<<
- 在 c++ 头文件中声明重载运算符时遇到问题