在函数中按引用调用

时间:2016-01-19 09:28:11

标签: c++ function

我在C++练习功能。在一些随机笔记中,我找到了一个按值调用的函数和通过引用调用的示例。

代码是

#include <string.h>
#include <iostream>
#include<stdio.h>

using namespace std;

void F1(float a, float b)
{
    a++;b++;
}

void F2 (float &a, float &b)
{
    a++;
    b++;
}
int main ()
{
    float a=9,b=5;

    float *ptrA=&a;
    float *ptrB=&b;

    F1(a,b);
    cout<<"\na:"<<a<<"\nb:"<<b;
    F2(a,b);
    cout<<"\na:"<<a<<"\nb:"<<b;
}

现在对于函数F2,我很困惑,在main函数中我传递了a和b的值,并且在定义中它接收了变量a和b的地址。那么如何在a和b的值中完成增量?

2 个答案:

答案 0 :(得分:1)

电话

F2(a,b);

实际发送a和b的地址,而不是它们的值,因为F2的声明方式。在C ++中,引用就像指针一样,只是语法更清晰。因此F2实际获取a和b的地址,然后a ++和b ++对main()中定义的原始变量进行操作。

答案 1 :(得分:0)

看起来你是在将浮点指针传递给函数

之后
void F1(float a, float b)
{
    a++;b++;
}

void F2 (float* a, float* b)
{
    a++;
    b++;
}

int main()
{
    float a, b;
    a = 5;
    b = 7;
    F1(a, b);
    // a is still 5 and b 7
    F2(&a, &b);
    // a is 6 b is 8
}
相关问题