c++ 使用引用防止类的拷贝构造

来源:互联网 发布:淘宝怎么买微博小号 编辑:程序博客网 时间:2024/06/08 17:45

举一个例子,例子中类的成员函数返回了类的引用,从而避免了类的拷贝构造,提高了效率

#include <iostream>#include <vector>#include <cstdio>using namespace std;class VectorRef{    std::vector<int> vecInts;public:    VectorRef(int size = 5)    {        for (int i = 0; i < size; i++)        {            vecInts.push_back(i);        }    }    **std::vector<int>& GetVecIns()**    {        return vecInts;    }};void PrintVecInts(**const std::vector<int> &vecInts**){    printf("\n");    for (size_t i = 0; i < vecInts.size(); i++)    {        printf("%d cur value = %d\n", i, vecInts[i]);    }}void TestVecInts(){    VectorRef vRef;    **vector<int>& v = vRef.GetVecIns();**    v.at(0) = 100;    PrintVecInts(v);    PrintVecInts(vRef.GetVecIns());}int main(){    TestVecInts();    return 0;}
0 0
原创粉丝点击