7
Reply

Overloaded stream insertion operator << in C++

Ken H

Ken H

Nov 24 2012 8:12 AM
5.8k

 hi friend,
    i have a program,but i do not understand function overloading reference type.

code,see below:
#include <iostream>
#include<string>
using namespace std;
class Employee
{
public:
    Employee(char *n,char *s,int a,char *depar,double sal)
 {
  strcpy(Name,n);
  strcpy(Sex,s);
  strcpy(Department,depar);
  Age=a;
  Salary=sal;
 }
 friend ostream& operator<<(ostream&,Employee&);
private:
 char Name[10];      
 char Sex[6];        
 int Age;            
 char Department[14];
 double Salary;      
};
ostream& operator<<(ostream& stream,Employee& obj)//why function return values and first parameter in use a reference type?
                                                                                              //I want to know what they represent and  execution process?
{
    stream<<"Name:"<<obj.Name<<'\n';
    stream<<"Sex:"<<obj.Sex<<"\n";
    stream<<"Age:"<<obj.Age<<"\n";
    stream<<"Department:"<<obj.Department<<"\n";
    stream<<"Salary:$"<<obj.Salary<<"\n";
    return stream;
}
int main()
{
        Employee emp1("AA","Male",23,"SoftDevelop",6300.5),
       emp2("BB","Male",35,"SoftDdevlop",4000);
       cout<<"\t\tEmployee Information\t\t"<<"\n";
       cout<<emp1<<"\n-------------------\n"<<emp2;
       return 0;
}


thanks

Answers (7)