zoukankan      html  css  js  c++  java
  • 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;
    }

    运行结果截图:

  • 相关阅读:
    各种排序
    最大子数组的和与积
    字符串距离
    二叉树的基本操作
    C++11创建线程的几种方式
    二分查找
    汉诺塔问题
    读写锁实现
    全排列
    数字转汉字
  • 原文地址:https://www.cnblogs.com/likemao/p/8509275.html
Copyright © 2011-2022 走看看