c++ - Operator overloading, need an explanation -
this question has answer here:
there code:
class precision { int digits; public: precision(int digits) : digits(digits) {} friend ostream& operator<<(ostream& os, const precision& p) { os.precision(p.digits); return os; } };
it's meant make command line like:
cout << precision(5) << << " " << precision(2) << b << endl;
to work, instead of doing:
cout.precision(5); cout << << " "; cout.precision(2); cout << b << endl
i fail understand how friend function part works. why friend? , how come receives 2 arguments instead of one? thanks.
it friend can access private value digits
.
the 2 arguments come compiler matching cout << precision(5)
call operator<<(cout, precision(5))
. operator returns refence stream, used next part stream << a
, etc.
Comments
Post a Comment