简体   繁体   中英

How to overload “operator %” in c++

I want to overload the % operator in c++, in order to avoid editing a huge block of code by hand. I tried this:

static float operator %(const float& left, const float& right);

In my header, but it wont work because "nonmember operator requires a parameter with class or enum type". I'm relatively new to C++, what am I supposed to do?

Operator overloads must have at least one of their arguments as a user-defined type. So you cannot do this.

What that means is that you cannot overload an operator when all the operands are non-class/enum types. ie, you cannot override the behaviour of % when both sides are float (or int , or any other primitive type).

As has already been stated, you cannot define overloaded operators for intrinsic types.

However, if you are willing to take advantage of implicit type conversion you can achieve something close to what you require with a single cast to one of your floats on a wrapper type that implements an overloaded% operator.

class FloatWrapper
{
private:
    float m_Float;

public:
    FloatWrapper(float Value):
      m_Float(Value)
    {
    }

    friend float operator%(const FloatWrapper& lhs, const FloatWrapper& rhs)
    {
        //your logic here...
        return (int)lhs.m_Float % (int)rhs.m_Float;
    }
};

int main()
{
float Value1 = 15.0f;
float Value2 = 4.0f;

float fMod1 = (FloatWrapper)Value1 % Value2;
float fMod2 = Value1 % (FloatWrapper)Value2;
return 0;
}
class Test
{
public:
     float operator%(float);
};

In C++ you need not to declare the operator as static, as opposed to C#. The argument can be of any type and the return value can also be. The first type would be the class itself.

Example:

Test test;
float x = test % 10.2f;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM