c++如何通过引用返回 vector ?

标签 c++ pointers vector reference header-files

我是一名 C++ 学生,需要一些帮助来理解和完成我的这部分作业。

我有一个 SalesItem 对象的 vector :

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

我需要返回那个 vector 作为引用:

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

现在,我知道给我错误的东西显然是错误的,我什至没有任何指针或引用。我发布的那几行代码只是作为我希望看到的示例(或者更现实地说,是对我有意义的示例。)

我想要一个像其他 get 函数一样工作的 get 函数,用于 int 或 string 等类型,除了这个函数必须通过引用返回(根据赋值的要求。)

不幸的是,我对 vector 和引用的理解不足以解决这个问题,而且我没有任何教育资源可以帮助我解决这个问题。如果有人可以帮助我理解该怎么做,我将不胜感激。

我们很乐意提供任何额外信息。

最佳答案

您需要指定返回类型。此外,最好同时提供 constnon-const 版本。代码如下:

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

示例用法:

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

关于c++如何通过引用返回 vector ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23233170/

相关文章:

c++ - 如何在 C++ 中打印成员函数地址

c++ - vector resize 抛出 bad_alloc 是否会使原始数据无效?

c++ - Point vector 中的 push_back() 不起作用

c++ - 在Qt中,发现所有窗口都关闭了,当使用QApplication::processEvents()时?

c++ - 涉及指针和手动实现的矩阵类的问题

c++ - 类有一个 selftype 的对象

c++ - 从 C++ 中的方法访问指向对象的私有(private)指针数组

c++ - 比 map<string, map<string, vector> 更好的东西

c++ - 有没有办法在 Visual Studio 2010 的 C++ 模板类中禁用成员函数(没有默认函数模板参数)

c++ - 如何固定 SIFT 关键点的数量?