Use reference as a return type

Using reference as a return type returns the address of an object, which can be a left value.

1. The stream operator << and >> return a reference type.

istream& operator>> (bool& val );
ostream& operator<< (bool val);

Thanks to the reference return type, we can use

cin>>m>>n; or

cout<<m<<n;

2. The assignment operator= returns a reference type.

C++:
01 class A
02 {
03 public:
04 
05     int b;
06     int c;
07     void print(void);
08     void set(int, int);
09     A& operator =(A a)
10     {
11         b=a.b;
12         c=a.c;
13         return (*this);
14     }
15 };
16 
17 void A::print(void)
18 {
19     cout<<“b= “<<b<<endl;
20     cout<<“c= “<<c<<endl;
21 }
22 
23 void A::set(int x, int y)
24 {
25     b=x;
26     c=y;
27 }
28 
29 int main()
30 {
31     A p;
32     p.set(1,2);
33     p.print();
34     A q=p;
35     q.print();
36 }
b=1
c=2
b=1
c=2
Advertisements
This entry was posted in C++. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s