Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The method of using the reference of Cstroke + as the return value of a function

2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

The content of this article introduces the relevant knowledge of "Champact + reference as the method of function return value". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Syntax: type & function name (formal parameter list) {function body}

Pay special attention to:

1. When a reference is used as the return value of a function, the & must be preceded by the function name when defining the function

two。 The greatest advantage of using a reference as the return value of a function is that it does not produce a copy of the return value in memory

/ / Code source: RUNOOB

# include

Using namespace std

Float temp

Float fn1 (float r) {

Temp=r*r*3.14

Return temp

}

Float & fn2 (float r) {/ / & indicates that it returns a reference to temp, in other words, temp itself

Temp=r*r*3.14

Return temp

}

Int main () {

Float a=fn1 (5.0); / / case 1: return value

/ / float& b=fn1 (5.0); / / case 2: use the return value of the function as the initialization value of the reference [Error] invalid initialization of non-const reference of type 'float&' from an rvalue of type' float'

/ / (some compilers can compile the statement successfully, but will give a warning)

Float c=fn2 (5.0); / / case 3: returns a reference

Float & d=fn2 (5. 0) / / case 4: use the reference returned by the function as the initialization value of the new reference

Cout

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report