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!!
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.
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.
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. However, 2 * u does not work, because 2 is not a statistician, and int is not a class with a member operator*.
For this to work right, you should define a non-member operator* and make it a friend of statistician:
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.
加载中,请稍侯......
精彩评论