什么原因导致C ++编译器错误:必须有类的参数或枚举类型? [英] What causes C++ compiler error: must have argument of class or enumerated type?

查看:612
本文介绍了什么原因导致C ++编译器错误:必须有类的参数或枚举类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

函式宣告:

  
template< typename T>
Point< T> * operator +(Point< T const * const point,Vector< T> const * const vector);

从我使用C ++开始已经有一段时间,所以也许我做的事真的很蠢。

解决方案



div>

你在语言层面做错了什么是重载操作符的指针。重载运算符的至少一个参数必须是用户定义的类型或对一个的引用。



但是你也在另一个级别上做错了。你返回一个指针,这意味着你可能需要在操作符中动态分配一些存储。那么,谁拥有这个存储?谁会释放它?



您应该参考并返回值,如:

  template< typename T> 
Point< T>运算符+(Point< T> const& point,Vector< T> const& vector){
return point T(point.x + vector.x,point.y + vector.y);
}


Function declaration:


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

这篇关于什么原因导致C ++编译器错误:必须有类的参数或枚举类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆