Overloading += operator in C++ - How do you pass t

2019-09-08 10:06发布

问题:

I need to create an operator that accepts a double 'parameter'.

myClass myobject();

double mydouble = 10000;

mydouble += myobject;

My operator:

double operator+=(double value, const myclass& object)
{
    value += object.value;           
    return  value;
}

The parameter value is being passed to the operator += as zero, even though mydouble is initialized to 10000.

How do you create an operator that can accept the left operand as a parameter?

回答1:

The correct prototype is the following:

double& operator+=(double& value, const myClass& obj)