When to Use Reference Arguments

2016-09-28  本文已影响0人  皮尼斯鳗鱼

C++ Primer Plus

There are two main reasons for using reference arguments:

The second reason is most important for larger data objects, such as structures and classobjects.These two reasons are the same reasons you might have for using a pointer argu-ment.This makes sense because reference arguments are really just a different interface for
pointer-based code. So when should you use a reference? Use a pointer? Pass by value?The following are some guidelines.

A function uses passed data without modifying it:

A function modifies data in the calling function:

Of course, these are just guidelines, and there might be reasons for making differentchoices. For example, cin uses references for basic types so that you can use cin >> ninstead of cin >> &n.

上一篇 下一篇

猜你喜欢

热点阅读