指针参数与引用参数

指针形参与引用参数

指针形参

指针作形参时,若在函数中修改指针对象的值,则对应实参的值会对应修改。

#include <iostream>
using namespace std;

void Change( int *p){
    *p=400;
};

int main(int argc, char const *argv[])
{
    int value = 1;
    int *argsPiont = &value;
    Change(&value);
    std::cout << "number4="<< value  <<endl;
    //console:value=400    
    std:cout<< "*argsPiont=" << *argsPiont << "\targsPiont=" << argsPiont << endl;
    //console: *p1=400 p1=0x5ffe54
    return 0;
}

若在函数体中仅修改指针的指向,则不会改变实参的值。

#include <iostream>
using namespace std;

void NoneChange(int *p)
{
    int value = 300;
    p = &value;
    *p = 400;
};

int main(int argc, char const *argv[])
{
    int value = 1;
    int *argsPiont = &value;
   
    std::cout << "value=" << value << endl;
    // console:value=1
    std::cout<< "*argsPiont=" << *argsPiont << "\targsPiont=" << argsPiont << endl;
    // console: *argsPiont=400 argsPiont=0x5ffe54
    std::cout << "=============" << endl;
    NoneChange(argsPiont);
    std::cout << "value=" << value  << endl;
    // console:value=1
    std::cout<< "*argsPiont=" << *argsPiont << "\targsPiont=" << argsPiont << endl;
    // console: *argsPiont=1 argsPiont=0x5ffe54
    return 0;
}

另外的,指针常量和常量指针也可以作为指针形参。只是二者根据需要限定了指针的指向不能修改或者是指针指向的对象不能修改。

指针的指向不能修改,但是指向的值可以修改等同于引用形参

引用参数

void Change(int &p)
{
    p = 400;
    //会修改实参的值。   

};
int main(int argc, char const *argv[])
{
    int value = 1;
    int *argsPiont = &value;
     Change(value);
    std::cout << "value=" << value << endl;
    // console:argsPiont=400
    std::cout<< "*argsPiont=" << *argsPiont << "\targsPiont=" << argsPiont << endl;
    // console: *argsPiont=400 argsPiont=0x5ffe54
}

引用参数会修改实参,若不能修改实参的值则可以用 const修订引用参数。

指向指针的引用

void Change(int *&p)
{
    int changeValue = 400;
    p = &changeValue;
    std::cout << "&changeValue=" << &changeValue << "\tchangeValue=" << changeValue << endl;
    //consle:&changeValue=0x5ffe1c   changeValue=400
};
int main(int argc, char const *argv[])
{
    int value = 1;
    int *argsPiont = &value;
    std::cout << "value=" << value << "\t&value=" << &value << endl;
    //console:value=1 &value=0x5ffe5c
    Change(argsPiont);
    std::cout << "*argsPiont=" << *argsPiont << "\targsPiont=" << argsPiont << endl;
    // console: *argsPiont=0    argsPiont=0x5ffe1c
}

指向指针的引用可以修改形参指针的指向。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值