當我們希望修改某個函數的返回值時,通常我們會返回這個值的引用(因為函數返回值其實是返回那個值得一份拷貝而已,所以想要修改必須使用引用):
.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; }
運行結果截圖: