As a function can be created to return a value of aprimitive type, a function can also be defined to return a reference to aprimitive type. When declaring such a function, you must indicate that it isreturning a reference by preceding it with the & operator. Here is anexample:
double & GetWeeklyHours(){}
In the body of the function, defined the desired behavior ofthe function as you see fit. The most important rule to apply is that thefunction must return not only a reference but a reference to the appropriatetype. When returning the value, don't precede the name of the variable with&. Here is an example:
double & GetWeeklyHours(){ double h = 46.50; double &hours = h; return hours;}
When calling a function that returns a reference, you canproceed as if it returns a regular value but of the appropriate type. Here is anexample:
//---------------------------------------------------------------------------#include
This would produce:
Weekly Hours: 46.5
No comments:
Post a Comment