鱼C论坛

 找回密码
 立即注册
查看: 1083|回复: 0

[技术交流] C语言传值-传址-传引用【转载】

[复制链接]
发表于 2019-11-26 18:17:16 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 糖逗 于 2019-11-29 16:17 编辑

原文链接:https://blog.csdn.net/flowing_wind/article/details/81225139
原文链接:https://www.cnblogs.com/tianqizhi/p/10255621.html

传值、传址和传引用
  在编写个人函数的时候,你将受到C++中一条基本原则的限制:在默认的情况下,参数只能以值传递的方式给函数。这句话的理解是:被传递到函数的只是变量的值,永远不会是变量本身。举例如下:
#include <iostream>

void changeAge( int age, int newAge );

// 如果想要实现计划功能,需要怎么改?
 
main()
{
    int age = 24;
    std::cout << "My age is " << age << "\n";
    
    changeAge( age, age+1 );
    
    std::cout << "Now my age is " << age << "\n";
}

void changeAge( int age, int newAge )
{
    age = newAge;
    std::cout << "In this , my age is " << age << "\n";
}


My age is 24
In this , my age is 25
Now my age is 24
请按任意键继续. . .


  绕开“值传递”问题的第一种方法是向函教传递变量的地址取代它的值。我们说C语言强大,有很大一部分就是在于他的灵活,他的灵活,有大一部分就是可以利用指针进行委婉地乱改。。。正如我们所理解的,想要获取某个变量的地址只需要在它前边加上一个“取地址”操作符(&)就行了。
  那我们可以试着这样:changeAge(&age,age+1)

#include <iostream>

void changeAge( int *age, int newAge );

// 如果想要实现计划功能,需要怎么改?
 
main()
{
    int age = 24;
    std::cout << "My age is " << age << "\n";
    
    changeAge( &age, age+1 );
    
    std::cout << "Now my age is " << age << "\n";
}

void changeAge( int *age, int newAge )
{
    *age = newAge;
    std::cout << "In this , my age is " << *age << "\n";
}


My age is 24
In this , my age is 25
Now my age is 25
请按任意键继续. . .


注意:如果传过去的是地址,在函教中必须要通过“*”对指针进行解引用,除非你有其他用途。


练习题:swap.cpp


#include <iostream>

void swap( int *x, int *y );

main()
{
    int x, y;
    
    std::cout << "请输入两个不同的值:";    
    std::cin >> x >> y;
    
    swap( &x, &y );
    
    std::cout << "调换后输出:" << x << ' ' << y << "\n\n"; 
}

void swap( int *x, int *y )
{
    int temp;
    temp = *x;
    *x = *y;
    *y = temp;
}



  另外的一种不需要中有的互换方案:swap2.cpp


#include <iostream>

void swap( int *x, int *y );

main()
{
    int x, y;
    
    std::cout << "请输入两个不同的值:";    
    std::cin >> x >> y;
    
    swap( &x, &y );
    
    std::cout << "调换后输出:" << x << ' ' << y << "\n\n"; 
}

void swap( int *x, int *y )
{
    //利用异或操作 
    *x ^= *y;
    *y ^= *x;
    *x ^= *y;
}



引用传递
  传址在我们看来已经是很不错,不过C++语言的大神们在完善的过程中完善了地址这个概念。
  设想:如果事先就知道某个函数的参数只能接受一个地址,能不能使用某种约定使得在调用该函数时不需要使用指针的语法呢?
  于是乎,以引用传递方式传递输入方式的概念因比而产生了。
  其实他跟我们这个传址的目的是一样的,都是把地址传递给函数,但语法不同更加容易使用了。以swap举例如下:
#include <iostream>

void swap( int &x, int &y ); //引用传递:声明时接受的是地址 

main()
{
    int x, y;
    
    std::cout << "请输入两个不同的值:";    
    std::cin >> x >> y;
    
    swap( x, y );
    
    std::cout << "调换后输出:" << x << ' ' << y << "\n\n"; 
}

void swap( int &x, int &y )
{
    int temp;
    temp = x;
    x = y;
    y = temp;
}
捕获.PNG
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-10-4 23:25

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表