简体   繁体   English

c ++如何通过引用返回向量?

[英]c++ How to return a vector by reference?

I'm a c++ student and could use some help with understanding and doing this part of my assignment. 我是一名c ++学生,可以帮助理解并完成我的任务。

I have a vector of SalesItem objects: 我有一个SalesItem对象的向量:

class Invoice
{
public:
    //blabla
    vector<SalesItem> *getSalesItems(); //code provided by the assignment.
private:
{
    //blabla
    vector<SalesItem> salesItems;
};

and I need to return that vector as a reference: 我需要将该向量作为参考返回:

void Invoice::getSalesItems() //error on this line. Code provided by assignment.
{
    return salesItems; //error on this line.
}

Now, I know that the things that are giving me errors are obviously wrong, I don't even have any pointers or references in there. 现在,我知道给我错误的东西显然是错误的,我甚至没有任何指针或参考。 I'm posting those few lines of code just as an example of what I would like to see (or more realistically, what makes sense to me.) 我发布这几行代码只是作为我希望看到的一个例子(或者更现实地说,对我有意义。)

I want a get function that works like other get functions for types like int or string, except this one has to return by reference (as required by the assignment.) 我想要一个get函数,它像int或string这样的类型的其他get函数一样工作,除了这个函数必须通过引用返回(根据赋值的要求)。

Unfortunately, my understanding of vectors and references is not up to merit for this problem, and I do not have any educational resources that can help me on this. 不幸的是,我对矢量和参考文献的理解不符合这个问题的优点,而且我没有任何教育资源可以帮助我解决这个问题。 If someone could please help me understand what to do, I would greatly appreciate it. 如果有人能帮助我理解该怎么做,我将不胜感激。

Any extra information will be gladly given. 我们很乐意提供任何额外的信息。

You need to specify the return type. 您需要指定返回类型。 Moreover, it is better to provide both const and non-const versions. 而且,最好同时提供constnon-const版本。 Code as follows: 代码如下:

class Invoice
{
public:
          vector<SalesItem> &getSalesItems()       { return salesItems; }
    const vector<SalesItem> &getSalesItems() const { return salesItems; }
private:
    vector<SalesItem> salesItems;
};

Sample usage: 样品用法:

Invoice invoice;
vector<SalesItem> &saleItems = invoice.getSalesItems(); // call the first (non-const) version
const Invoice &const_invoice = invoice;
const vector<SalesItem> &saleItems = const_invoice.getSalesItems(); // call the second (const) version

You are returning void in the function implementation. 您在函数实现中返回void And you also don't have correct declaration to get return by reference. 并且您也没有正确的声明来通过引用返回。

The code should be like this: 代码应该是这样的:

Header: 标题:

class Invoice
{
public:
    vector<SalesItem> &getSalesItems();
private:
    vector<SalesItem> salesItems;
};

Implementation: 执行:

vector<SalesItem> &Invoice::getSalesItems() {
    return salesItems;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM