// overload ostream insertion operator<< friend ostream &operator<< (ostream &stm, Frac const &rhs) { stm << rhs.num << “/” << rhs.den; }
Overloading the Stream Insertion Operator (<<)
To enable seamless integration of custom data types with C++’s standard output streams, such as std::cout, the stream insertion operator (<<) must be overloaded. For a class Frac representing a fraction, this allows an object of the class to be printed in an intuitive and readable format, just like a built-in type.
The standard approach is to implement this overload as a non-member function. Since the function needs to access the private members of the Frac class (specifically, num and den), it is declared as a friend inside the class definition.
class Frac {
int num, den;
public:
// ... other members and constructors ...
// Friend declaration for the stream insertion operator
friend std::ostream& operator<<(std::ostream& stm, Frac const& rhs);
};
// Function implementation
std::ostream& operator<<(std::ostream& stm, Frac const& rhs) {
stm << rhs.num << "/" << rhs.den;
return stm;
}
content_copydownloadUse code with caution.C++
Explanation
This implementation follows a standard, robust pattern for operator overloading. Let’s break down the function signature: std::ostream& operator<<(std::ostream& stm, Frac const& rhs).
- Return Type (std::ostream&): The function returns a reference to an ostream object. This is crucial for enabling chaining of output operations. For instance, in the statement std::cout << f1 << ” and ” << f2;, the expression std::cout << f1 is evaluated first. It calls the overloaded operator, which prints the fraction and then returns the std::cout stream itself. This returned stream then becomes the left-hand operand for the next << operator, allowing the chain to continue.
- Function Name (operator<<): This is the special name C++ uses to signify an overload of the << operator.
- First Parameter (std::ostream& stm): This is a reference to the output stream that the object is being sent to (e.g., std::cout). It is passed as a non-const reference because the act of writing to the stream modifies its internal state.
- Second Parameter (Frac const& rhs): This is the object to be printed—the right-hand side of the << operator. It is passed as a constant reference (const&) for two key reasons: efficiency (avoiding a costly copy of the object) and safety (guaranteeing that the print operation does not modify the object).
The function body simply sends the numerator, a slash character, and the denominator to the stream stm. Finally, returning stm ensures the operator can be used in chained expressions.thumb_upthumb_down
