模板运算符在源文件而不是标头中重载

时间:2013-04-29 19:59:31

标签: c++ templates header operator-overloading

我制作了一个简单的Vector2模板类,用于存储XY值。现在我正在尝试在源文件中继续执行模板,但是我无法通过运算符重载

来执行此操作
    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

亲切的问候,我

1 个答案:

答案 0 :(得分:3)

您对operator +的定义缺少返回类型:

    template <class Type>
    Vector2<Type> Vector2<Type>::operator+ (const Vector2<Type> &other)
//  ^^^^^^^^^^^^^
    {
        return Vector2<Type>(x + other.x, y + other.y);
    }

另请注意,类模板的成员函数的定义应出现在包含类模板定义的同一标头中,除非您对将以其他方式隐式创建的所有实例化使用显式实例化(请参阅{{3} })。