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
Class Definition The following is the general format of defining a class template: class tag_name                  {                    public  :               // Must

explain Storage management: free storage pool, garbage collection, compaction, boundary tag method; Hash tables and hashing functions

kirchoff''s law

Conversion Functions Conversion functions are member functions used for the following purposes: 1. Conversion of object to basic data type. 2. Conversion of basic data ty

Greatest Common Divisor (GCD) - The greatest common divisor (GCD) of two integers is the largest integer that will evenly divide both integers. The GCD algorithm involves intege

how to find minimum number if shelves required



Manipulators There are several classes in the iostream.h header file. One of them is ios class. This class stores the format state. For example, some bits explain the base in w

defining software crisis As the technology changes rapidly the requirement for the users' change, to part the growing demand of the user for trade,  business, and personal