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
I have a Matlab assignment and I have the assignment description+ algorithm + and the output sample. the files are on a dropbox folder and you can download them from the link below

Rules of Operator Overloading It is a function defined to an operator with new term or meaning. It cannot produce new operator. It cannot modified the meaning of th

Binary search in array: - C program: Write a program in c to define binary search in array. void main()                 {                 clrscr();

write a program to find the area under the curve y=f(x) between x=a and x=b integrate y=f(x) between the limits of a and b #include float start_point,

The program must use the file named on the command line as its input file. Suppose the program is named pdbtool. Then if the user types pdbtool 1A36.pdb the program must read the d

Why PHP is sometimes called as embedded scripting language? PHP is a high level language that is used to allow users to write and understand it in human readable form and also

A: N delete p is a two-step procedure: it calls the destructor, and then releases the memory. The code developed for delete p is functionally similar to this (supposing p is of typ

A palindrome is a string that reads the same from both the ends. Given a string S convert it to a palindrome by doing character replacement. Your task is to convert S to palindrome

Explain  U s e r - D e f i n e d D a t a T y p es? C has Union and Structure as user-defined data types.  C++ has class which looks like structure with a

Write out pseudocode for a function called "and" that takes two arguments, both booleans, and returns the logical and of the inputs. DO NOT use the logical and operator: instead, w