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 the purpose of pointer ? what is the syntax? how it works?


Is friend function can be harmfull to make a secure program/sofware?

Smugglers are becoming very smart day by day. Now they have developed a new technique of sending their messages from one smuggler to another. In their new technology, they are send

Consider the following algorithm to generate a sequence of numbers. Start with an integer n. If n is even, divide by 2. If n is odd, multiply by 3 and add 1. Repeat this process wi

when a class is defined the compiler will not allocate memory. This is true only for data member not for member function.  As soon as the member function is defined  the require

Project Description: We own proprietary software which long ago had Copyminder protection added. We no longer have the source code or a relationship with the original coder and

Compiler Design - Limit In The Method Instructions

Destructors A destructor function gets implemented whenever an instance of the class to which it belongs goes out of existence. The primary usage of a destructor function is