二进制“*” :未找到采用“statistician”类型的全局运算符; (或者没有可接受的转换)
我试图重载我的运算符,它实际上只是一个包含算术函数和数组变量序列的类。
但是当我重载我的 (*) 乘法运算符时,我收到此错误:
binary '*' : no global operator found which takes type 'statistician'
(or there is no acceptable conversion)
当我的代码尝试执行以下操作时会发生这种情况: s = 2*u;
in main.cpp
其中 s 和 u 是统计学家类。
statistician = 我的班级
(statistician.h)
class statistician
{
... other functions & variables...
const statistician statistician::operator*(const statistician &other) const;
..... more overloads...
};
任何帮助都会很棒,谢谢!!
I am trying to overload my operators its really just a class that holds arithmetic functions and a sequence of array variables.
But when i am overloading my (*) multiplication operator i get this error:
binary '*' : no global operator found which takes type 'statistician'
(or there is no acceptable conversion)
This happens when my code tries to do: s = 2*u;
in main.cpp
where s, and u are statistician classes.
statistician = my class
(statistician.h)
class statistician
{
... other functions & variables...
const statistician statistician::operator*(const statistician &other) const;
..... more overloads...
};
Any help would be awesome thanks!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
声明一个命名空间范围
operator*
,这样您就可以在左侧拥有一个非类型的可转换操作数统计学家。
不用说,您应该删除类内的,并且您需要一个转换构造函数来获取
int
。Declare a namespace scope
operator*
, so that you can also have a convertible operand on the left hand side that is not of typestatistician
.Needless to say that you should remove the in-class one then, and you need a converting constructor to take the
int
.这正是为什么像 * 或 + 这样的二元运算符应该是非成员的原因。
如果您执行了
s = u * 2
,它就会起作用,假设您有一个用于statistician
的非显式构造函数,该构造函数采用单个int
> 论证。但是,2 * u
不起作用,因为 2 不是statistician
,并且int
不是具有成员运算符的类*。
为了使其正常工作,您应该定义一个非成员
operator*
并使其成为statistician
的friend
:您还需要定义其他版本的
operator*
接受整数(或您希望能够“相乘”的任何其他类型)或为statistician
定义非显式构造函数以启用隐式转换。This is exactly why binary operators like * or + should be non-member.
If you did
s = u * 2
, it would have worked, assuming that you have a non-explicit constructor forstatistician
that takes a singleint
argument. However,2 * u
does not work, because 2 is not astatistician
, andint
is not a class with a memberoperator*
.For this to work right, you should define a non-member
operator*
and make it afriend
ofstatistician
:You also need to either define other versions of
operator*
that take integers (or whatever other types you wish to be able to "multiply") or define non-explicit constructors forstatistician
to enable implicit conversion.