编程语言
首页 > 编程语言> > C++引用与指针

C++引用与指针

作者:互联网

引用与指针之间的区别:

#include <iostream>

using namespace std;

int main()
{
   

    int a = 10;
    float b = 21.2;

    int &r_a = a;
    float &r_b = b;

    cout << "a : " << a << endl;
    cout << "a的引用 : " << r_a << endl;
    cout << "b : " << b << endl;
    cout << "b的引用 : " << r_b << endl;


    return 0;
}

输出结果:

a : 10      
a的引用 : 10
b : 21.2
b的引用 : 21.2

将引用作为函数参数:

#include <iostream>

using namespace std;

void Swap(int &a, int &b)
{
    int temp = a;
    a = b;
    b = temp;
}

int main()
{
    int a,b;
    cin >> a >> b;

    cout << "交换前 a :" << a << endl;
    cout << "交换前 b :" << b << endl;
    Swap(a,b);

    cout << "交换后 a :" << a << endl;
    cout << "交换后 b :" << b << endl;

    return 0;
}

输出结果:

100
200
交换前 a :100
交换前 b :200
交换后 a :200
交换后 b :100

引用作为函数返回值,可以作为左值

#include <iostream>
 
using namespace std;
 
double vals[] = {10.1, 12.6, 33.1, 24.1, 50.0};
 
double& setValues(int i) {  
   double& ref = vals[i];    
   return ref;   // 返回第 i 个元素的引用,ref 是一个引用变量,ref 引用 vals[i]
 
 
}
 
// 要调用上面定义函数的主函数
int main ()
{
 
   cout << "改变前的值" << endl;
   for ( int i = 0; i < 5; i++ )
   {
       cout << "vals[" << i << "] = ";
       cout << vals[i] << endl;
   }
    
   setValues(1) = 20.23; // 改变第 2 个元素
   setValues(3) = 70.8;  // 改变第 4 个元素
 
   cout << "改变后的值" << endl;
   for ( int i = 0; i < 5; i++ )
   {
       cout << "vals[" << i << "] = ";
       cout << vals[i] << endl;
   }
   return 0;
}

输出结果:

改变前的值
vals[0] = 10.1
vals[1] = 12.6
vals[2] = 33.1
vals[3] = 24.1
vals[4] = 50
改变后的值
vals[0] = 10.1
vals[1] = 20.23
vals[2] = 33.1
vals[3] = 70.8
vals[4] = 50

 

标签:cout,int,C++,引用,vals,ref,指针
来源: https://www.cnblogs.com/boost/p/16246615.html