开发者

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 h开发者_Go百科eader, 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. i.e., 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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜