質問

I'm fairly new to c++ and am trying to learn about custom operators. The problem I'm having currently is in relation to defining my own += operator and the best way to go about it. This involves a simple class with a public int member (intValue) that can be added to. The following two code examples, which I've tried one at a time, operate exactly the same in my program as far as I can tell. By 'exactly the same' I mean I get the same result and create the same number of objects.

Which one is more correct (standard practice) and why?

Utility& operator +=(Utility& left, Utility right)
{
    return left = left + right;
}

Or

void operator +=(Utility& left, Utility right)
{
    left = left + right;
}

And, if it matters, the operator they call:

Utility operator +(Utility left, Utility right)
{
    return Utility(left.intValue + right.intValue);
}

The class prints out a message any time its constructor is called so I can tell if a new object is being made. Based on that the two forms of += I'm trying here result in the same number of objects being created.

役に立ちましたか?

解決

Since += normally modifies its left-hand operand, you'd generally rather not implement it in terms of operator+ (which needs to create a temporary value to hold the result).

Likewise, since you can't reasonably do a conversion on the left operand, it should really be a member function.

Utility &Utility::operator+=(Utility const &right) { 
    intValue += right.intValue;
    return *this;
}

他のヒント

Generally, one would expect += to modify the left hand operand, it would be better if you avoid implementing it with operator + that results in creating a temporary value.

Besides,

Utility& operator +=(Utility& left, Utility right)
{
    return left = left + right;
}

is better than the other in the sense that it returns the result. This enables users to write compound expressions like:

Utility utility1 , utility2;
Utility ut += (utility1 += utility2);

But if you can modify the Utility internally without operator+, it would be better.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top