📜  在C ++中通过引用返回示例

📅  最后修改于: 2021-06-01 00:40:59             🧑  作者: Mango

C++中的指针引用彼此之间保持着密切的关系。主要区别在于,可以像添加值一样操作指针,而引用只是另一个变量的别名

  • C++中的函数可以返回引用,因为它返回了指针
  • 当函数返回引用时,表示返回隐式指针。

通过引用返回与通过引用返回非常不同。当变量或指针作为引用返回时,函数起着非常重要的作用

请参阅下面的“按引用返回”的函数签名:

下面是说明按引用返回的代码:

CPP
// C++ program to illustrate return by reference
#include 
using namespace std;
  
// Function to return as return by reference
int& returnValue(int& x)
{
  
    // Print the address
    cout << "x = " << x
         << " The address of x is "
         << &x << endl;
  
    // Return reference
    return x;
}
  
// Driver Code
int main()
{
    int a = 20;
    int& b = returnValue(a);
  
    // Print a and its address
    cout << "a = " << a
         << " The address of a is "
         << &a << endl;
  
    // Print b and its address
    cout << "b = " << b
         << " The address of b is "
         << &b << endl;
  
    // We can also change the value of
    // 'a' by using the address returned
    // by returnValue function
  
    // Since the function returns an alias
    // of x, which is itself an alias of a,
    // we can update the value of a
    returnValue(a) = 13;
  
    // The above expression assigns the
    // value to the returned alias as 3.
    cout << "a = " << a
         << " The address of a is "
         << &a << endl;
    return 0;
}


C++
// C++ program to illustrate return
// by reference
#include 
using namespace std;
  
// Global variable
int x;
  
// Function returns as a return
// by reference
int& retByRef()
{
    return x;
}
  
// Driver Code
int main()
{
    // Function Call for return
    // by reference
    retByRef() = 10;
  
    // Print X
    cout << x;
    return 0;
}


输出:
x = 20 The address of x is 0x7fff3025711c
a = 20 The address of a is 0x7fff3025711c
b = 20 The address of b is 0x7fff3025711c
x = 20 The address of x is 0x7fff3025711c
a = 13 The address of a is 0x7fff3025711c

解释:

由于引用不过是另一个变量的别名(同义词)而已,因此abx的地址永远不会改变。

下面是说明按引用返回的代码:

C++

// C++ program to illustrate return
// by reference
#include 
using namespace std;
  
// Global variable
int x;
  
// Function returns as a return
// by reference
int& retByRef()
{
    return x;
}
  
// Driver Code
int main()
{
    // Function Call for return
    // by reference
    retByRef() = 10;
  
    // Print X
    cout << x;
    return 0;
}
输出:
10

解释:
上面函数retByRef()的返回类型是变量x的引用,因此将值10分配给x。

想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”