[英]binary '*' : no global operator found which takes type 'statistician' (or there is no acceptable conversion)
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;
当我的代码试图这样做时会发生这种情况:
s = 2*u;
in main.cpp 在main.cpp中
where s, and u are statistician classes. 其中s和u是统计学家。
statistician = my class 统计学家=我的班级
(statistician.h) (statistician.h)
class statistician
{
... other functions & variables...
const statistician statistician::operator*(const statistician &other) const;
..... more overloads...
};
Any help would be awesome thanks!! 任何帮助都会很棒,谢谢!!
Declare a namespace scope operator*
, so that you can also have a convertible operand on the left hand side that is not of type statistician
. 声明命名空间作用域
operator*
,这样您也可以在左侧有一个不属于statistician
类型的可转换操作数。
statistician operator*(const statistician &left, const statistician &right) {
// ...
}
Needless to say that you should remove the in-class one then, and you need a converting constructor to take the int
. 不用说你应该删除类中的那个,然后你需要一个转换构造函数来获取
int
。
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 for statistician
that takes a single int
argument. 如果你做了
s = u * 2
,它会有效,假设你有一个statistician
的非显式构造函数,它接受一个int
参数。 However, 2 * u
does not work, because 2 is not a statistician
, and int
is not a class with a member operator*
. 但是,
2 * u
不起作用,因为2不是statistician
,而int
不是具有成员operator*
。
For this to work right, you should define a non-member operator*
and make it a friend
of statistician
: 为了使其正常工作,您应该定义一个非成员
operator*
并使其成为statistician
的friend
:
statistician operator*(const statistician &left, const statistician &right);
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 for statistician
to enable implicit conversion. 您还需要定义其他版本的
operator*
,它们采用整数(或您希望能够“乘法”的任何其他类型),或者为statistician
定义非显式构造函数以启用隐式转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.