I'm a c++ student and could use some help with understanding and doing this part of my assignment.
I have a vector of SalesItem
objects:
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.)
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. 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With