View Full Version : C++ Help!!


§outh§tar
04-27-04, 08:13 PM
How do I overload the output stream operator for structures. I have this code but it only gives me an error. I know this is relatively simple, but please bear with me. :(

struct item
{
int id;
int inv;
apstring productName;
};


struct storeType
{
apvector <item> list;
int number;
};

ostream& operator<<(ostream& osObject, const storeType& object)
{
int x=0;

for (x=0; x<50; x++)
osObject << object.list[x].id << " " << object.list[x].inv << " " << object.list[x].productName << endl;
//Return the ostream object
return osObject;
}

Can anyone please tell me why this doesn't work when I try to output it. I am not allowed to use any other way but overloading the output stream so I'm stuck trying to figure this out:

void loadData(storeType &items)
{
cout << items; // I get the error here!
}

okinrus
04-27-04, 10:24 PM
It looks ok. I think apvector is a template class, though.

§outh§tar
04-27-04, 10:49 PM
apvector is an include file

I'm getting the error at:

cout << items;

items being of type storeType

I'm trying to overload cout to deal with objects of type storeType.

okinrus
04-28-04, 12:23 AM
I don't have the ap classes offhand but my conversion to stl works, with minor changes, so I suspect the problem is you're using the apvector wrong or your not including the write headers to use cout. Perhaps you want apvector<store>. The way you have would mean that apvector stores a generic object type like Java's vector class.

#include <iostream>
#include <vector>
#include <list>
using namespace std;

struct item
{
int id;
int inv;
string productName;
};


struct storeType
{
vector<item> list;
int number;
};

ostream& operator<<(ostream& osObject, const storeType& object)
{
typedef vector<item>::size_type SizeType;


for (SizeType x = 0; x < object.list.size(); x++)
osObject << object.list[x].id << " "
<< object.list[x].inv << " "
<< object.list[x].productName << endl;

//Return the ostream object
return osObject;
}

int main(void)
{
storeType foo;

cout << foo << endl;

return 0;
}