maolike

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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

.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  阅读(4915)  评论(0编辑  收藏  举报