The canonical form of the operator + = for classes

I know that it is a good idea to make as many non-member interfaces as possible, and I just realized that for my three-dimensional vector class "Vector3" I can move + =, - =, etc. statements outside the class, leaving only the constructors and copy assignment operator.

Question: what should this operator look like? I saw the canonical forms of many other operators and followed their advice, but I did not see the canonical forms of these operators. I have given what, in my opinion, should be lower.

Second question: what do these operators call? Arithmetic assignment operations?

Code (relevant):

class Vector3 { public: Vector3& operator+=(const Vector3& rhs); float x, y, z; }; Vector3& Vector3::operator+=(const Vector3 &rhs) { x += rhs.x; y += rhs.y; z += rhs.z; return *this; } 

What I have changed so far:

 class Vector3 { public: float x, y, z; }; Vector3& operator+=(Vector3& lhs, const Vector3& rhs) { lhs.x += rhs.x; lhs.y += rhs.y; lhs.z += rhs.z; return lhs; } 
+4
source share
3 answers

That you look good.

By the way, when you come to the + operator, this is usually implemented in terms of + =. (create a copy of lhs, then call lhs + = rhs and return the result)

I don’t know if you know about this trick, but since you are worried about the canonical ways to implement these operators, this will not hurt to mention it. :)

+2
source

That you look good.

The main way to think about it intuitively is to think about how you want the code to look when you write it. If in this case you can write

 Vector v, w; v += w; w += v; 

etc., you are on the right track.

There are many good rules to help you; see this entry in the C ++ FAQ for lots on it.

+1
source

I would not say "as much of the interface as possible." There is not much to do operator+= , operator-= etc. Not a friend, not a member.

Some people prefer to make each function a possible non-member function different from one another to resist the temptation to use private member variables. But you are an adult: you can write a function as an open member, and not use private member variables. I prefer to know that a function is bound to a class and makes it a public member makes it explicit.

Note:
Personally, I think that often use private members instead of the usual accessories (I know - I will burn in hell). Not always! - but often.
In fact, there are a few cases where you could not switch to public accessors within a few minutes if you decide that you need it. But I do not recognize this as a popular view, and I do not ask people to follow this philosophy.

There are specific reasons for certain functions and operators to be "not friends, not members." For example, the <() operator when used as the "stream insert operator" cannot be a member because you have to change the lhs (stream) class.

0
source

All Articles