i have a program,but i do not understand function overloading reference type.
code,see below:
#include
#include
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:"<
}
int main()
{
Employee emp1("AA","Male",23,"SoftDevelop",6300.5),
emp2("BB","Male",35,"SoftDdevlop",4000);
cout<<"\t\tEmployee Information\t\t"<<"\n";
cout<
}
thanks

VulpesPosted Nov 25, 2012, 12:48 PM
But, if you change the return type to void (including in the 'friend' declaration) and remove the line:
return stream;
then it will compile and run fine:
However, if you then change:
cout<
to:
cout<
then it won't compile because the expression:
cout<
now has a void return type (rather than ostream&) and so can't appear before another << operator.
This is what I meant when I said that the return type of the operator overload needs to be ostream& so it can used within a larger input/output expression.
Ken HPosted Nov 26, 2012, 5:31 AM
VulpesPosted Nov 26, 2012, 5:09 AM
Ken HPosted Nov 26, 2012, 3:45 AM
Its execution diagram below:
thanks
Ken HPosted Nov 26, 2012, 2:05 AM
Ken HPosted Nov 24, 2012, 10:19 PM
Other I understand, Below I do not understand:
Having a return value equal to the reference parameter might seem pointless at first but it enables the stream object to be used within a larger input/output expression.
will change code follows:
ostream operator<<(ostream& stream,Employee& obj)
{ stream<<"Name:"<
}
Main function using only a class of objects:
int main()
{
Employee emp1("AA","Male",23,"SoftDevelop",6300.5);
cout<<"\t\tEmployee Information\t\t"<<"\n";
cout<
return 0;
}
compile-time error.
thanks
VulpesPosted Nov 24, 2012, 2:07 PM