I'm trying to understand why are comparison operators are overloaded as an outside function:
class Test {
// private fields
public:
// methods
friend bool operator==(cons Test & t1, const Test & t2);
};
bool operator==(cons Test & t1, const Test & t2){
return (t1.fields==t2.fields);
}
rather than implement it inside the class:
class Test {
// private fields
public:
// methods
bool operator==(const Test & other){
return (this.fields==other.fields);
}
};
what other considerations can I use when deciding whether to overload an operator inside the class or outside it. when is it better to use fried? and when will i prefer using getters?
or perhaps a helper function to pass me private fields such as:
class Test {
// private fields
public:
// methods
ostream& print()(ostream& os){
os << this.private_field;
return os;
}
};
ostream& operator<<(ostream& os, const Test& t) {
return t.print(os);
}