C++ Class, What's the difference in friend operator vs outside operator -
C++ Class, What's the difference in friend operator vs outside operator -
when define operator function within class define within class function not part of class.
but same task achived when function outside class , declare friend within class not define it.
consider code have 2 identical operator definitions 1 within class ouside class:
version 1 (inside of class)
class myclass { // version 1 within class friend myclass&& operator +(myclass& a, myclass& b) { homecoming move(myclass(a.x + b.x, a.y + b.y)); } int x,y; public: myclass() {} myclass(int,int){} }; int main() { myclass a, b, c; c = + b; cin.ignore(); homecoming 0; }
version 2 (outside of class)
class myclass { friend myclass&& operator +(myclass& a, myclass& b); int x,y; public: myclass() {} myclass(int,int){} }; myclass&& operator +(myclass& a, myclass& b) { homecoming move(myclass(a.x + b.x, a.y + b.y)); } int main() { myclass a, b, c; c = + b; cin.ignore(); homecoming 0; }
what's difference in 2 approaches?
at moment, defining myclass&& operator +(myclass& a, myclass& b)
twice in first snippet , 1 time in second. if remove sec definition, 2 semantically equivalent.
the 2 same thing. in cases 1 may preferred on other (for example, sec can placed in cpp
file , first may more natural templates).
note first implicitly marked inline, sec not.
(you should passing myclass
const reference, though.)
c++ class operator-keyword friend
Comments
Post a Comment