什么导致 C++ 编译器错误:必须有类或枚举类型的参数?
函数声明:
template <typename T>
Point<T>* operator +(Point<T> const * const point, Vector<T> const * const vector);
我已经有一段时间没有使用 C++了,所以也许我正在做一些非常愚蠢的事情.让我知道.
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);
}
相关文章