模板操作符在源文件而不是头文件中重载

Template operator overload in source file instead of header

本文关键字:文件 重载 操作符 源文件      更新时间:2023-10-16

我做了一个简单的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

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)。