Class definition?

I am to write program using a class definition "Bag". I am new to class definition and don't quite understand them. The program is supposed to allow the user to enter a item until the user wants it to stop, and then display that item. I will show you what I have so far. What else to I need? Thank you.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
  #include <iostream>
using namespace std;

class Bag
{
  public:
  add();
  display();

};

int main()
{
  Bag grabBag;
  string item;

   // Test add()
  cout << "Enter an item ";
  getline(cin, item);
  while (item != "quit")
   {
     grabBag.add(item);
     cout << "Enter an item or 'quit': ";
     getline(cin, item);
   }
   grabBag.display();
}
You need to define what Bag::add() and Bag::display() actually do, i.e. write the code for those methods.

This will almost certainly require adding some data members to Bag, to hold whatever data it will need to store.
Last edited on
to allow the user to enter a item until the user wants it to stop, and then display that item


Presumably to display all the items that were entered?

class member functions need to have a body for them. Also there needs to be member variable to contain the added items (vector?). Consider:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <string>
#include <vector>

class Bag
{
public:
	void add(std::string& item) { data.push_back(item); }

	void display() const {
		for (const auto& d : data)
			std::cout << d << '\n';
	}

private:
	std::vector<std::string> data;
};

int main()
{
	Bag grabBag;

	for (std::string item; (std::cout << "Enter an item or 'quit': ") && std::getline(std::cin, item) && item != "quit"; grabBag.add(item));

	grabBag.display();
}



Enter an item or 'quit': qwe
Enter an item or 'quit': asd
Enter an item or 'quit': zxc
Enter an item or 'quit': quit
qwe
asd
zxc

Last edited on
Topic archived. No new replies allowed.