-4

There is this 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 to make a command line like:

cout << precision(5) << a << " " << precision(2) << b << endl; 

to work, instead of doing:

cout.precision(5);
cout << a << " ";
cout.precision(2);
cout << b << endl

I fail to understand how the friend function part works. Why is it a friend? And how come it receives two arguments instead of one? THanks.

Matam
  • 145
  • 7

1 Answers1

0

It is a friend so that it can access the private value digits.

The two arguments come from the compiler matching cout << precision(5) to a call operator<<(cout, precision(5)). The operator then returns a refence to the stream, which is used for the next part stream << a, etc.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203