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;
}

運行結果截圖:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM