Style guideline/convention for defining binary operator in a class (C++) -
this bit of general question, have classes i'd define binary "operations" on, , there several different ways of doing so. example, suppose have vector
class i'd implement addition operation on. on 1 hand, overload '+'
operator, have read few sources isn't practice (which begs 1 ask why language feature @ all). can see in many cases why methods preferable operator overloading, vector addition agreed upon , using '+'
should natural.
on other hand, define add()
method in class. define normal method , use x.add(y)
perform x + y
, doesn't showcase binary operator i'm not sure if should preferred. define static method, instance vector.add(x, y)
. finally, define add()
friend function of class, (mathematically) natural in opinion bit contrary philosophy of oop
. i'm hoping bit of insight methods preferable (and why).
the usual approach define reflexive operators (+=
, *=
, etc.) members modify object applied to, , define non-reflexive operators (+
, *
, etc.) non-members create copy of 1 of arguments, use corresponding reflexive operator operation, , return new object result.
while java programmers believe add
functions thing, because java doesn't have operator overloading. named operations lead really long , unreadable expressions things should simple.
Comments
Post a Comment