[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
TCPPSamCoutObject

cout<<AnyObject

This sample explains how you can provide printing for any object you choose (i.e. user defined object).

This is the same principle that is implemented in the header file complex.h. An object of type complex (say z1) can be outputted using a stream object such as cout as shown below:
complex z (4,3);
cout<<z;


Important Points

(Add)

Code

//objprt.cpp
//done in TC++ 3.0
//Program to illustruate printing for an object using cout the object
//version: 1.0
//created: 12.32pm IST, 25 dec 2006
  1. include<iostream.h>
class CompNum //simple complex class { private: int real, imag;//to store real and imaginary values public: CompNum()//constructor { real=imag=5; } CompNum(int r, int i)//overloaded constructor { real=r; imag=i; } void disp()//function to display real & imaginary values { cout<<real<<" + i "<<imag; } friend ostream& operator << (ostream& ostrobj, CompNum& CompObj)//creating friend function //returns reference to ostream object { return ostrobj << CompObj.real<<" + i "<<CompObj.imag; } };//end of class definition int main() { CompNum z1; CompNum z2(10,20); //displaying using in-built method cout<<"Normal output\n"; cout<<"z1 = "; z1.disp(); cout<<endl; cout<<"z2 = "; z2.disp(); cout<<endl; //displaying using cout object cout<<"With stream object\n"; cout<<"z1 = "<<z1<<endl; cout<<"z2 = "<<z2<<endl; }
Output
Normal ouput
z1 = 5 + i 5
z2 = 10 + i 20
With stream object
z1 = 5 + i 5
z2 = 10 + i 20

Comments

(add)

last edited (December 30, 2006) by bilderbikkel, Number of views: 1937, Current Rev: 5 (Diff)

[Edit this page]  [Page history]  [What links here]  [Discuss this topic]  [Printer Friendly]  

Members

Username:

Password:


Register
Forgot Password?




Programmers Heaven - for .NET, Java, C/C++ and WEB Developers!
© 1996-2008 Community Networks Ltd. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Development by Tore Nestenius at .NET Consultant - Synchron Data.