开发者

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

开发者 https://www.devze.com 2023-04-06 02:15 出处:网络
Function declaration: template <t开发者_开发知识库ypename T> Point<T>* operator +(Point<T> const * const point, Vector<T> const * const vector);

Function declaration:


template <t开发者_开发知识库ypename T>
Point<T>* operator +(Point<T> const * const point, Vector<T> const * const vector);

It's been a while since I've used C++ so maybe I'm doing something really stupid. Let me know.

Also, no, I am not using namespace std.


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);
}


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


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号