output an array class member
Sep 13, 2017 at 7:26pm UTC
Hello guys thanks in advance for your interest!
What is the conventional way to output data stored in your array class member?
not using a void member function and ostream.
I guess I need a function(maybe returning a pointer pointing to the array)
but how..? Please let me know how you would do in this case. That will be sincerely appreciated
this is my header
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <string>
#include <cassert>
class bag
{
public
static const unsigned short CAPACITY =10;
bag();
~bag();
void add(const std::string&)
private
std::string obj[CAPACITY];
unsigned short numOfobj;
}
This is my implemenation
1 2 3 4 5 6 7 8 9 10 11 12 13
const unsigned short bag::CAPACITY;
bag::bag(): numOfobj(0)
{
}
bag::~bag()
{
}
void bag::add(const std::string& strIn)
{
assert (numOfobj<CAPACITY);
ojb[numOfobj] = strIn;
++numOfobj;
}
This is my demo
1 2 3 4 5 6 7 8 9 10
int main()
{
bag temp;
temp.add("Apples" );
temp.add("Peachs" );
temp.add("Grapes" );
// How do I output the data here??
return 0;
}
Last edited on Sep 13, 2017 at 7:30pm UTC
Sep 13, 2017 at 7:48pm UTC
Ideally, you'd overload the << operator so you could say something like:
1 2 3
bag temp;
...
cout << temp << '\n' ;
If you haven't studied overloaded operators yet then create a member function called print() that will print out the members:
1 2 3 4 5 6 7 8
class bag {
public :
...
void print(ostream &os)
{
// add code to print the strings to os
}
};
And then in your main program:
1 2 3 4 5 6 7 8 9 10
int main()
{
bag temp;
temp.add("Apples" );
temp.add("Peachs" );
temp.add("Grapes" );
temp.print(cout);
return 0;
}
Topic archived. No new replies allowed.