c++引用(修改引用的值)

当我们希望修改某个函数的返回值时,通常我们会返回这个值的引用(因为函数返回值其实是返回那个值得一份拷贝而已,所以想要修改必须使用引用):

.h文件

#pragma once
#include <vector>
using namespace std;
class ref1
{
public:
    ref1();
    ~ref1();
    std::vector<int *> pVec;
    vector<int *>& getVec();
};

.cpp文件

#include "stdafx.h"
#include "ref.h"


ref1::ref1()
{
    int *p1 = new int(3);
    int *p2 = new int(3);
    int *p3 = new int(3);
    pVec.push_back(p1);
    pVec.push_back(p2);
    pVec.push_back(p3);
}


ref1::~ref1()
{
}

std::vector<int *>& ref1::getVec()
{
    return pVec;
}

接收引用并修改值:vector<int *>&tmpV = aa->getVec();

#include "ref.h"
using namespace std;
int main()
{
    ref1*aa = new ref1;
    vector<int *>&tmpV = aa->getVec();
    int *p4 = new int(5);
    int * &p5 = tmpV.at(0);//在容器中访问元素的成员函数(front,back,下标,at)返回的都是引用
    p5 = p4;
    cout << *(aa->pVec.at(0));
    system("pause");
    return 0;
}

运行结果截图:

 

posted on 2018-03-05 15:35 maolike 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/likemao/p/8509275.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值