a use operator overloading to present a friend


A: Use operator overloading to present a friend left-shift operator, operator<<.

#include class Fred {

public:

friend std::ostream& operator<< (std::ostream& o, const Fred& fred);

... private:

int i_; // only for illustration

};

std::ostream& operator<< (std::ostream& o, const Fred& fred)

{

return o << fred.i_;

}

int main()

{

Fred f;

std::cout << "My Fred object: " << f << "\n";

...

}

We employ a non-member function (a friend in this case) as the Fred object is the right-hand operand of the << operator. If the Fred object was imagined to be on the left hand side of the << (i.e., myFred << std::cout instead of std::cout << myFred), we could have utilized a member function named operator<<.

Note down that operator<< returns the stream. It is so the output operations can be cascaded.

 

Request for Solution File

Ask an Expert for Answer!!
C/C++ Programming: a use operator overloading to present a friend
Reference No:- TGS0217900

Expected delivery within 24 Hours