[Home]
[Edit this page]
[Recent Changes]
[Special Pages]
[Help]
TCPPSamCoutObject
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:
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
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 2006Outputclass 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; }
- include<iostream.h>
Normal ouput z1 = 5 + i 5 z2 = 10 + i 20 With stream object z1 = 5 + i 5 z2 = 10 + i 20
Comments
(add)[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
