What causes C++ compiler error: must have argument of class or enumerated type?

前端 未结 3 1928
忘掉有多难
忘掉有多难 2020-12-20 14:38

Function declaration:


template 
Point* operator +(Point const * const point, Vector const * const vector);


        
相关标签:
3条回答
  • 2020-12-20 15:06

    You can't overload operators for fundamental types, in your case both arguments are pointers. Did you want references instead?

    0 讨论(0)
  • 2020-12-20 15:07

    What you're doing wrong here on the language level is overloading operators for pointers. At least one argument of an overloaded operator must be of a user-defined type, or a reference to one.

    But you're also doing this wrong on another level. You're returning a pointer, which means you will probably need to allocate some storage dynamically in the operator. Well, who owns that storage? Who will release it?

    You should just take references and return by value, something like:

    template <typename T>
    Point<T> operator +(Point<T> const& point, Vector<T> const& vector) {
        return Point<T>(point.x + vector.x, point.y + vector.y);
    }
    
    0 讨论(0)
  • 2020-12-20 15:20

    When you define an operator, at least one of the arguments must be a user-defined class or enumerated type (or a reference to one of those). Pointers don't qualify as either of those. You should be using reference arguments, and returning an unqualified Point<T>.

    0 讨论(0)
提交回复
热议问题