Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

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

Shulou Source: shulou.com Published: 2022-06-02 10:20:54 09月14日 Update

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

Tags: Function variable situation memory object copy way source statement that is picture local Bole online polymorphic that is global alias copy member Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei MySQL Microsoft Redmi OPPO Reno