How can i present printing for my class fred?, C/C++ Programming

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.

 

Posted Date: 3/20/2013 8:14:22 AM | Location : United States







Related Discussions:- How can i present printing for my class fred?, Assignment Help, Ask Question on How can i present printing for my class fred?, Get Answer, Expert's Help, How can i present printing for my class fred? Discussions

Write discussion on How can i present printing for my class fred?
Your posts are moderated
Related Questions
WHAT IS A C LANGUAGE? C IS A PROGRAMMING?

Illustrate the Function Definition? The C code that explains what a function does is called the function definition. A function definition has the following form Type fun

HOW TO USE POINTER

Define the Stream Oriented Data Files? There are two dissimilar types of data files called stream-oriented (or standard) data files and system-oriented (or low-level) data file

Write a recursive implementation of Euclid's algorithm for finding the greatest common divisor (GCD) of two integers. Descriptions of this algorithm are available in algebra books

Rahul is a newbie to the programming and while learning the programming language he came to know the following rules: ???• Each program must start with ''{'' and end with '

A Padovan string P(n) for a natural number n is defined as: P(0) = ‘X’ P(1) = ‘Y’ P(2) = ‘Z’ P(n) = P(n-2) + P(n-3), n>2 where + denotes string concatenation. For a string of the c

Project Description: We are seeking online invoice OCR solution. That will help us to automate accounts payable function. User should be able to use the offered pdf file or s

Available in the string.h header file are the following routines         strcat(string1,string2);   This joins string2 to string1; care must be taken to allocate enough space for

What if one forget the [] when deleteing array allocated through new T[n]? A: All life comes to a disastrous end. It is the programmer's responsibility not the compiler's to